无法使用 fs 读取 .txt 的内容

Unable to read content of .txt using fs

我正在使用 fs 模块读取 .txt 文件内容,但结果始终为空。我的 .txt 文件确实有内容,有人可以帮我吗?这是我的测试代码:

var fs = require("fs");

var content = "";
fs.readFile("2.txt", "utf8", function(err, data){
  if(err) {
    return console.log("fail", err);
  }
  content = data;
});

console.log(content);

content 在控制台中是空的。

你写结果太早了。您应该在 readFile 回调中记录结果。

var fs = require("fs");

var content = "";
fs.readFile("2.txt", "utf8", function(err, data){
  if(err) {
    return console.log("fail", err);
  }
  content = data;
  console.log(content);
});
// The console log below will be executed right after the readFile call. 
// It won't wait the file to be actually read.
// console.log(content);

或者你可以这样写同样的逻辑:

const fs = require('fs');

async function main() {
  try {
    const content = await fs.promises.readFile('2.txt', 'utf8');
    console.log(content);
  } catch (ex) {
    console.trace(ex);
  }
}

main();