簡體   English   中英

為什么我的 fs 錯誤在 Node.js 中返回一個空的 object?

[英]Why is my fs error returning an empty object in Node.js?

我目前正在嘗試使用 Node v12.16.2 中的fs讀取文件。 我目前有一個 function 設置,如下所示:

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.log ing err.messageerr.valueOf和使用throw err ,這些都沒有給我更多關於錯誤的數據。 如果有人可以幫助發現我的問題或已經知道它,我將不勝感激。

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');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM