Skip to content

Instantly share code, notes, and snippets.

@joepie91
Last active December 5, 2017 11:48
Show Gist options
  • Save joepie91/c6aa1ee552dcac821d03 to your computer and use it in GitHub Desktop.
Save joepie91/c6aa1ee552dcac821d03 to your computer and use it in GitHub Desktop.
Node.js callbacks
var fs = require("fs");
function readJSON(filename, callback) {
fs.readFile(filename, function(err, file) {
if (err != null) {
return callback(err);
} else {
var parsedFile = JSON.parse(file);
return callback(null, parsedFile)
}
})
}
readJSON("./sample.json", function(err, parsedFile) {
if (err != null) {
console.log("It broke!", err);
} else {
console.log(parsedFile);
}
})
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));
function readJSON(filename) {
return Promise.try(function(){
return fs.readFileAsync(filename);
}).then(function(file){
return JSON.parse(file);
})
}
Promise.try(function(){
return readJSON("./sample.json");
}).then(function(parsedFile){
console.log(parsedFile);
}).catch(function(err){
console.log("It broke!", err);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment