Async.series 不适用于 fs.readFile
Async.series doesn't work with fs.readFile
第一步,我想将文件加载到名为"file"的变量中,然后在第二步,do response.write(file)
为了实现这一点,我使用了async.series,但我的代码有问题。
这是我用来启动服务器的代码:
var http = require("http"),
fs = require('fs'),
async = require('./js/async.js');
var onRequest = function(request,response) {
response.writeHead(200,{ "Content-Type": "text/html; charset=utf-8" });
var file; // 'file' declared
var main = function(callback) {
fs.readFile('.''html''admin.html','utf-8',function(err,data) {
file = data; // 'file' is given content of admin.html
console.log('2 >> ' + typeof file);
});
callback(null);
}
console.log('1 >> ' + typeof file);
async.series([
main
], function() { // At this point 'file' is still undefined, that's odd
response.end(); // 'cause it's a callback and should be fired after 'main'
console.log('3 >> ' + typeof file);
});
}
http.createServer(onRequest).listen(80);
问题在于主题 - async.series 没有像我希望的那样工作:在触发来自 async.series 的回调后,"main"函数中的 fs.readFile 返回数据。
我得到这个输出:
1 >> undefined
3 >> undefined
2 >> string
虽然我期望:
1 >> undefined
2 >> string
3 >> string
问题出在哪里?
尝试将回调添加到 readFile
var main = function(callback) {
fs.readFile('.''html''admin.html','utf-8',function(err,data) {
file = data; // 'file' is given content of admin.html
console.log('2 >> ' + typeof file);
callback(null);
});
}
也许在我们的情况下最好使用瀑布?,像这样
async.waterfall([
function (callback) {
fs.readFile('.''html''admin.html','utf-8', function (err, data) {
callback(err, data);
});
}
], function (err, file) {
response.end();
})
相关文章:
- 为什么fs.readFile在windows上花费太多时间
- 为什么这个 fs.readFile 循环没有将其结果推送到我的数组
- Node res.write() and fs.readFile
- 使用Node.js'fs.readFile()返回字符串出现的行
- 节点.js解析 fs.readFile() 的意外数字转换
- fs.readFile 的替代方法,用于在 Express 中使用 res.json 时加载车把模板
- 使用 require vs fs.readFile 读取 json 文件内容
- Angular 没有从 FS.readFile 获取带有承诺的数据
- Async.series 不适用于 fs.readFile
- Javascript / NodeJs - fs.readFile 在读取文件之前使用回调
- 从 fs.readFile 获取数据
- Hapijs、fs.readfile、fs.writefile和childprocess.exec我如何控制异步
- 存储nodejs fs.readfile's产生一个变量并传递给全局变量
- 为什么fs.readFile返回缓冲区
- 为什么我不能使用响应?写入fs.readFile
- javascript回调-处理读取文件与fs.readFile
- 在fs.readfile在使用fs.readfile.bind(context,pathArgument)时被调用
- fs.readFile返回Buffer对象,toString将使终端报错
- React和Electron with Bablify: Uncaught TypeError: fs.readFile
- TypeError: fs.readFile不是一个函数