编写readfile/write文件的nodejs函数的更好方法

cod*_*Gig 1 javascript node.js express

我怎样才能以更好的方式编写这段代码.

var fs = require('fs');

var file = '/test.txt';  
fs.readFile(file, 'utf8', function (err, txt) {  
    if (err) return console.log(err);

    txt = txt + '\nAppended something!';
    fs.writeFile(myFile, txt, function (err) {
        if(err) return console.log(err);
        console.log('Appended text!');
    });
});
Run Code Online (Sandbox Code Playgroud)

假设我有多个回调,那么我们如何防止回调的回调等等....

getData(function(a){  
    getMoreData(a, function(b){
        getMoreData(b, function(c){ 
            getMoreData(c, function(d){ 
                getMoreData(d, function(e){ 
                    ...
                });
            });
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

Jor*_*rix 6

我真的很喜欢蓝鸟:

首先,你必须'promisify' fs.在下面的例子中,他们直接宣传该readFile方法:

var readFile = Promise.promisify(require("fs").readFile);

readFile("myfile.js", "utf8").then(function(contents) {
    return eval(contents);
}).then(function(result) {
    console.log("The result of evaluating myfile.js", result);
}).catch(SyntaxError, function(e) {
    console.log("File had syntax error", e);
//Catch any other error
}).catch(function(e) {
    console.log("Error reading file", e);
});
Run Code Online (Sandbox Code Playgroud)

要么:

var fs = Promise.promisifyAll(require("fs"));
// note now you have to put 'async' after the methods like so:
fs.readFileAsync("myfile.js", "utf8").then(function(contents) {
    console.log(contents);
}).catch(function(e) {
    console.error(e.stack);
});
Run Code Online (Sandbox Code Playgroud)