Skip to content

Instantly share code, notes, and snippets.

@Nicolab
Last active August 29, 2015 14:06
Show Gist options
  • Save Nicolab/01f4c06a8171a8adf6fc to your computer and use it in GitHub Desktop.
Save Nicolab/01f4c06a8171a8adf6fc to your computer and use it in GitHub Desktop.
Example of updateJson() with promise
var promise = require('bluebird');
var fs = primise.promisifyAll(require('fs'));
function updateJson(ticker, value) {
fs.readFileAsync('stocktest.json', 'utf8')
.then(function(contents) {
var stocksJson = JSON.parse(contents);
if (!stocksJson[ticker]) {
throw new Error(ticker + ' doesn\'t exist on the json');
}
stocksJson[ticker].price = value;
return fs.writeFileAsync('stocktest.json', JSON.stringify(stocksJson, null, 4));
})
.then(function() {
console.log('File successfully written');
})
.catch(function(error) {
console.error(error);
})
.error(function(error) {
console.error('unable to read file, because: ', error.message);
})
;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment