简体   繁体   English

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

[英]better way of writing nodejs function of readfile/write file

How can i write this code in a better way. 我如何以更好的方式编写此代码。

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

Suppose i have multiple callback then how can we prevent this callback of callback and so on.... 假设我有多个回调,那么我们如何才能防止这种回调回调等等。

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

I really like bluebird for this: 我真的很喜欢蓝鸟

First you have to 'promisify' fs . 首先,您必须“承诺” fs n the example below they directly promisify the readFile method: 在下面的示例中,它们直接实现了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);
});

or: 要么:

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

I suggest async waterfall 我建议异步瀑布

Your first snippet would look like following: 您的第一个片段如下所示:

var txt;

async.waterfall([
    function(callback) {
        fs.readFile(file, 'utf8', callback);
    },
    function(txt, callback) {
        txt = txt + '\nAppended something!';
        fs.writeFile(myFile, txt, callback);
    },
    function(callback) {
        console.log('Appended text!');
        callback();
    }   
], function (err, result) {
    console.log(err)
});

What you're describing is callback hell and there's a couple of smart ways to get around it. 您所描述的是回调地狱,有两种巧妙的解决方法。 I don't claim to be the know it all but there's a whole website called callbackhell.com that you might want to check out. 我并不声称自己一无所知,但是有一个整个网站叫做callbackhell.com ,您可能想查看一下。

But for the short answer, you can do these things 1. keep your code shallow, or name your functions 但是对于简短的答案,您可以执行以下操作:1.保持代码浅浅,或为函数命名

Instead of writing your fs.readFile with an anonymous function, name it and call it like so 不用使用匿名函数编写fs.readFile,而是像这样命名并调用它

fs.readFile(file, 'utf8', function readFileCb(err, txt) {  
 if (err) throw new Error(err);

 txt = txt + '\nAppended something!';
 fs.writeFile(myFile, txt, function (err) {
    // no need to return a console.log, just throw Error should suffice
    if(err) throw new Error(err); 
    console.log('Appended text!');
 });
});   

2. Modularize your code. 2.模块化您的代码。 Have named functions or libraries that do exactly one thing 已命名的函数或库仅完成一件事

function writeFile(file, txt, cb){
  fs.writeFile(file, txt, cb)
}

function writeFileCb(err){
 if(err) throw new Error(err);
 console.log('Appended Text!');
}

fs.readFile(file, 'utf8', function readFileCb(err, txt) {  
 if (err) throw new Error(err);

 txt = txt + '\nAppended something!';
 writeFile(myFile, txt, writeFileCb);
});   

3. Ensure that all errors are caught. 3.确保捕获所有错误。 You seem to be doing that well, so kudos! 您似乎做得不错,所以赞!

You can also use Promises, libraries like Async waterfall, but callbacks are an essential parts of JavaScript and going through callback hell is just a matter of having good sense in writing your code. 您也可以使用Promises,Async Waterfall之类的库,但是回调是JavaScript的重要组成部分,而通过回调地狱只是编写代码时的明智之举。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM