【问题标题】:Missing Callback function缺少回调函数
【发布时间】:2013-11-28 08:20:21
【问题描述】:
function onRequest(req, res) {
    if (req.body.widget_name) {
        console.log(req.body.widget_name);
    }
    var fs = require('fs');
    var data = fs.readdir("corpdashboard/dashboards", 'UTF-8', function (err, files) {
        if (err) {
            return console.log(err);
        }
        console.log(data);
    });
    var body = req.body.dashboard_selected + ' ' + req.body.widget_selected + ' ';
    res.setHeader('Content-Type', 'text/plain');
    res.setHeader('Content-Length', body.length);
    res.end(body);
}
exports.onrequest = onRequest;

我想读取目录和其中的文件,所以我编写了这段代码并运行它。在运行时我得到那个 fs:missing 回调函数 :ENOENT readdir 'D:\dev\corpdashboboard\dashboard.js' 'D:\dev\corpdashboboard' 是我有我的 ejs 文件和 js 文件的地方 这是什么意思? 我应该怎么做才能读取其中的目录和文件

【问题讨论】:

  • 移除第二个参数('UTF-8')。
  • 如果您希望其他人阅读您的代码,请正确缩进。

标签: javascript node.js


【解决方案1】:

来自官方规范:http://nodejs.org/api/fs.html#fs_fs_readdir_path_callback

fs.readdir(path, callback)
Asynchronous readdir(3). Reads the contents of a directory.
The callback gets two arguments (err, files) where files is
an array of the names of the files in the directory excluding '.' and '..'.

您使用了错误的参数。 fs.readdir() 不接受编码。所以readdir 期望path 是一个字符串,callback 是一个函数。

应该是:

var data = fs.readdir('corpdashboard/dashboards',function (err, files) {
    if (err) {
         return console.log(err);
    }
    console.log(data);
});

【讨论】:

    【解决方案2】:

    给任何阅读本文的人的注意事项:上述答案有效的,但在 Node v6.x 中,fs.readdir 确实接受了一个额外的参数,您可以在文档中看到它。 https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback

    如果您遇到此问题,请检查以确保您运行的是 Node v6.0.0 或更高版本。

    【讨论】:

    • 这应该是对主题答案的评论。
    • ^ 我没有足够的代表。
    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多