【问题标题】:node.js callbacks http server read dirnode.js 回调 http 服务器读取目录
【发布时间】:2015-07-24 11:30:27
【问题描述】:

菜鸟有一些问题,无法让脚本显示文件列表,我认为是关于 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'

【问题讨论】:

  • 试图将过滤器移动到回调没有成功

标签: javascript node.js http fs


【解决方案1】:

在您的任何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);

【讨论】:

  • Thks,它只是完美.. 一个问题在这种情况下,我是否会在第一个文件上丢失任何“异步”?问候,
  • @user1958517 - 我不确定您所说的“松开任何异步”是什么意思?
猜你喜欢
  • 2011-08-14
  • 1970-01-01
  • 2022-01-13
  • 2014-11-13
  • 2014-09-22
  • 1970-01-01
  • 2018-02-21
  • 1970-01-01
  • 2014-10-06
相关资源
最近更新 更多