菜鸟有一些问题,无法使脚本显示文件列表,我认为关于walk是异步的,但是我没有任何帮助的错误。
问候,马塞洛
// ---- listFiles.js -----------------------------------------------------------
exports.walk = function(currentDirPath, extension, callback) {
var fs = require('fs');
var regex = new RegExp( extension + '$', 'g' );
fs.readdir( currentDirPath, function (err, files) {
if (err) callback(err);
files.filter(function(fname){
if(fname.match(regex)) {
callback(null, fname);
}
})
});
console.log("Fired callback.");
}
// walk('.', 'js', function(err, file){ console.log(file); }); runs OK
// ---- listfilesTest.js --------------------------------------------------------
var http = require('http');
var content = require('./listFiles');
var args = process.argv.slice(2);
console.log(args); // command line arguments (dir & extension)
http.createServer(function (req, res) {
var files = [];
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('-- list of files --\n');
content.walk(args[0], args[1], function(err, data){
if(err) console.error(err);
//console.log(data);
res.write(data); // not printing the dir Listings
} );
res.end();
}).listen(9000);
// nodemon listFilesTest.js '.' 'js'
您res.end()
在res.write()
执行任何语句之前都在打电话。对的回调content.walk()
是异步的,这意味着它会在未来的不确定时间内发生。
您需要在res.end()
所有res.write()
语句完成后调用。这种方式exports.walk()
是结构化的,调用者无法知道何时完成列出文件并调用回调,因此必须对其进行重组以指示完成时间。
有很多可能的方法来构造它。一种相当简单的方法是,仅在回调中添加一个参数,该参数会在列表完成时发出信号。
// ---- listFiles.js -----------------------------------------------------------
exports.walk = function(currentDirPath, extension, callback) {
var fs = require('fs');
var regex = new RegExp( extension + '$', 'g' );
fs.readdir( currentDirPath, function (err, files) {
if (err) callback(err);
files.filter(function(fname){
if(fname.match(regex)) {
// call the callback with this filename, not done yet
callback(null, false, fname);
}
})
// signal that we are done listing the files
callback(null, true);
console.log("Done listing files.");
});
}
// walk('.', 'js', function(err, done, file){ console.log(file); }); runs OK
// ---- listfilesTest.js --------------------------------------------------------
var http = require('http');
var content = require('./listFiles');
var args = process.argv.slice(2);
console.log(args); // command line arguments (dir & extension)
http.createServer(function (req, res) {
var files = [];
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('-- list of files --\n');
content.walk(args[0], args[1], function(err, done, data){
if(err) {
console.error(err);
return;
}
if (done) {
res.end();
} else {
//console.log(data);
res.write(data); // not printing the dir Listings
}
});
}).listen(9000);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句