第一步,我想将文件加载到名为“file”的变量中,然后在第二步,
执行response.write(文件)
为了实现这一点,我使用 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 无法按照我期望的方式工作:“main”函数中的 fs.readFile 在 async.series 的回调被触发后返回数据。
我得到这个输出:
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);
});
}
也许在我们的例子中更好地使用 waterfall ?,就像这样
async.waterfall([
function (callback) {
fs.readFile('.\\html\\admin.html','utf-8', function (err, data) {
callback(err, data);
});
}
], function (err, file) {
response.end();
})
关于javascript - Async.series 不适用于 fs.readFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27194040/