javascript - 更好的编写读取文件/写入文件的nodejs函数的方法

标签 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!');
    });
});

假设我有多个回调那么我们怎样才能防止这个回调等等....

getData(function(a){  
    getMoreData(a, function(b){
        getMoreData(b, function(c){ 
            getMoreData(c, function(d){ 
                getMoreData(d, function(e){ 
                    ...
                });
            });
        });
    });
});

最佳答案

我很喜欢bluebird为此:

首先你必须“ promise ”fs。在下面的示例中,他们直接 promise 了 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);
});

或者:

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);
});

关于javascript - 更好的编写读取文件/写入文件的nodejs函数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36872889/

相关文章:

javascript - 发布请求 express : Cannot set headers after they are sent to the client

javascript - 我如何在 dynamicHepler 中渲染一个部分?

javascript - 版本更改时 Node 段错误

javascript - Mongoose - 在保存文档之前为每个对象生成 ObjectID

javascript - 在 es6 javascript 类的非静态成员函数中调用静态 getter

javascript - 从 PHP 脚本调用 Node

javascript - 在网站上运行 node.js 但不在本地主机上运行

javascript - 选择任何选项时未捕获的类型错误 : Cannot read property 'current' of null - Select2. js

scrollbar - 滚动到位置 (javascript)

javascript - 如何使用 Javascript 在网站中单击 SVG 的一部分?