var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

日志未定义,为什么?


当前回答

var path = "index.html"

const readFileAsync = fs.readFileSync(path, 'utf8');
// console.log(readFileAsync)

我使用简单的readFileSync即可。

其他回答

var path = "index.html"

const readFileAsync = fs.readFileSync(path, 'utf8');
// console.log(readFileAsync)

我使用简单的readFileSync即可。

我喜欢使用fs-extra,因为所有函数都是承诺的,开箱即用,所以可以使用await。所以你的代码可以是这样的:

(async () => {
   try {
      const content = await fs.readFile('./Index.html');
      console.log(content);
   } catch (err) {
      console.error(err);
   }
})();

如前所述,fs。readFile是一个异步动作。这意味着当您告诉节点读取一个文件时,您需要考虑这将花费一些时间,同时,节点继续运行以下代码。在你的例子中,它是:console.log(content);。

这就像把代码的一部分发送到很远的地方(比如读取一个大文件)。

看看我写的评论:

var content;

// node, go fetch this file. when you come back, please run this "read" callback function
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});

// in the meantime, please continue and run this console.log
console.log(content);

这就是为什么当您记录内容时,内容仍然是空的。Node尚未检索到文件的内容。

这可以通过在回调函数中移动console.log(content)来解决,就在content = data;之后。这样,您将在节点读取文件以及内容获得值之后看到日志。

var fs = require('fs');
var path = (process.cwd()+"\\text.txt");

fs.readFile(path , function(err,data)
{
    if(err)
        console.log(err)
    else
        console.log(data.toString());
});

在ES7中使用Promises

与mz/fs异步使用

mz模块提供了核心节点库的承诺版本。使用它们很简单。首先安装库…

npm install mz

然后……

const fs = require('mz/fs');
fs.readFile('./Index.html').then(contents => console.log(contents))
  .catch(err => console.error(err));

或者你也可以在异步函数中写它们:

async function myReadfile () {
  try {
    const file = await fs.readFile('./Index.html');
  }
  catch (err) { console.error( err ) }
};