【问题标题】:Why is my fs error returning an empty object in Node.js?为什么我的 fs 错误在 Node.js 中返回一个空对象?
【发布时间】:2020-09-21 08:22:02
【问题描述】:

我目前正在尝试在 Node v12.16.2 中使用 fs 读取文件。我目前有这样的功能设置:

const fs = require('fs');
var JSONData;
const read = function(path){
    fs.readFile(path, 'utf8', (data, err) => {
        if(err){
            console.log(err);
            console.log('there was an error');
        }
        JSONData = data;
    })
}
read('./path/to/file.json');

在控制台中,我只是得到

{}
there was an error

我还尝试了console.loging err.messageerr.valueOf 和使用throw err,但这些都没有给我更多关于错误的数据。如果有人能帮助发现我的问题或已经知道我的问题,我将不胜感激。

【问题讨论】:

  • 路径是有效路径吗?
  • @Chana 我相信是这样,尽管我无法真正确认,因为错误不起作用:/。我正在使用与我开始使用的文件相关的目录(与 fs 一样),但通常当它无效时它会告诉我......
  • 您应该先传递错误,然后再传递数据。 (err, data)nodejs.org/api/errors.html

标签: javascript node.js json error-handling fs


【解决方案1】:

Node.js 中的回调将错误作为第一个参数接收:

const fs = require('fs');
var JSONData;
function read (path) {
    fs.readFile(path, 'utf8', (err, data) => { // <-- Look here
        if (err) {
            console.log(err);
            console.log('there was an error');
        }
        JSONData = data;
    })
}
read('./path/to/file.json');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-06
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2021-12-04
    • 2018-02-23
    相关资源
    最近更新 更多