Last active
August 29, 2015 14:06
-
-
Save Nicolab/01f4c06a8171a8adf6fc to your computer and use it in GitHub Desktop.
Example of updateJson() with promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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