Create a gist now

Instantly share code, notes, and snippets.

Avoiding Nested Callbacks in Javascript
var fs = require('fs');
fs.mkdir('./hello',0777,makeDirectory);
function makeDirectory(err){
if (err) throw err;
fs.writeFile('./hello/world.txt', 'Hello!', writeFile);
}
function writeFile(err){
if (err) throw err;
console.log('File created with contents: ');
fs.readFile('./hello/world.txt', 'UTF-8', readFile);
}
function readFile(err, data){
if (err) throw err;
console.log(data);
}
var fs = require('fs');
function writeHello(){
return fs.writeFile('./hello.txt', 'Hello!', writeFile);
function writeFile(err){
if (err) throw err;
console.log('Wrote hello.txt');
}
}
function writeWorld(){
return fs.writeFile('./world.txt', 'World!', writeFile);
function writeFile(err){
if (err) throw err;
console.log('Wrote world.txt');
}
}
writeHello();
writeWorld();
var fs = require('fs');
fs.mkdir('./hello',0777,function(err){
if (err) throw err;
fs.writeFile('./hello/world.txt', 'Hello!', function(err){
if (err) throw err;
console.log('File created with contents: ');
fs.readFile('./hello/world.txt', 'UTF-8', function(err, data){
if (err) throw err;
console.log(data);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment