读取文件/写入文件的nodejs函数的更好的方法
我怎样才能以更好的方式编写这段代码?
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!'); }); });
假设我有多个callback,那么我们怎样才能防止callback等callback….
getData(function(a){ getMoreData(a, function(b){ getMoreData(b, function(c){ getMoreData(c, function(d){ getMoreData(d, function(e){ ... }); }); }); }); });
我真的很喜欢bluebird :
首先你必须'promisify'fs。 下面的例子他们直接promisify 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); });
我build议asynchronous瀑布
您的第一个片段如下所示:
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) });
你所描述的是callback地狱,有几个聪明的方法来解决它。 我不认为是所有人都知道,但有一个叫做callbackhell.com的整个网站,你可能想看看。
但是对于简短的回答,你可以做这些事情1.保持你的代码浅,或命名你的function
不要用匿名函数写你的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.模块化您的代码。 已经命名的函数或库完成一件事情
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.确保所有错误都被捕获。 你似乎做得很好,所以很荣幸!
你也可以使用Promises,像Async瀑布这样的库,但是callback是JavaScript的重要组成部分,通过callback地狱只是在编写代码时有一个很好的意义。