gpt4 book ai didi

javascript - node.js 回调 http 服务器读取目录

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:28:38 25 4
gpt4 key购买 nike

有一些问题的菜鸟,无法使脚本显示文件列表,我认为是关于 walk is async,但我在错误中没有任何帮助。

问候,马塞洛

// ---- 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.write() 语句执行之前调用了 res.end()content.walk() 的回调是异步的,这意味着它会在未来某个不确定的时间发生。

您需要在所有 res.write() 语句完成后调用 res.end()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);

关于javascript - node.js 回调 http 服务器读取目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31601110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com