从Node.js中的fs.readFile返回对象

问题描述 投票:0回答:1

我正在尝试在下面返回jsonObj,但没有返回。帮助将不胜感激。这里的fileName是我需要读取的文件的路径。再次,我需要返回jsonObj。所以我可以在fs.readFile函数之外访问它。''这是代码

return fs.readFile(fileName, 'utf-8', (err, fileContent) => {
  if(err) {
     console.log(err); // Do something to handle the error or just throw it
     throw new Error(err);
  }
  let jsonObj = csvjson.toObject(fileContent);
  console.log(jsonObj)
  return jsonObj
});
node.js
1个回答
0
投票

在Node中,您不会从回调函数中获得return,该函数会被丢弃并忽略。您必须使用Promises(可能与async / await结合使用),或者必须接受自己的回调函数。

这是异步代码的基础:

// The fs.readFile() function executes immediately
fs.readFile(..., (err, ...) => {
   // This code runs in the distant future, like imagine ten years from now
   // from the perspective of the computer.
});

// JavaScript continues here immediately.

readFile函数没有特别返回任何内容,内部函数尚未运行。还值得注意的是,在其中抛出异常是没有意义的,不要这样做。

链接至:

function getData(fileName, cb) {
  fs.readFileName(fileName, 'utf-8', (err, fileContent) => {
    if (err) {
      // Back-propagate the error
      return cb(err);
    }

    // Engage the callback function with the data
    cb(null, csvjson.toObject(fileContent));
  }
}

请注意,如果您改用诺言,则此代码的复杂程度将大大降低。

© www.soinside.com 2019 - 2024. All rights reserved.