fs.readFile函数的响应为undefined...有什么想法吗?

4

我正在运行一个简单的readfile命令,用于视频教程,这是完全按照导师保存的代码...

var fs = require("fs");
console.log("Starting");
fs.readFile("./sample.txt", function(error, data) {
console.log("Contents: " + data);
});
console.log("Carry on executing");

我在与此js文件相同的文件夹中有一个sample.txt文件,在sample.txt文件中我有"This is a sample output for this text document",不幸的是,代码中的data变量输出为"undefined"。 如果有人知道为什么会发生这种情况,希望能提供帮助... 谢谢。

1
在回调函数的第一行添加 if (error) throw error;,看看能否得到任何提示。 - Pointy
(或只需console.log(error)。) - Pointy
ENOENT 的意思是文件不存在。 - Pointy
但是..........文件....就在那里......就在目录中。 - Christopher Allen
那么,当您(使用Cygwin)执行ls 'C:\ Users \ Jenny Kemp \ sample.txt'时,您是否看到该文件? - Pointy
显示剩余2条评论
3个回答

5

首先尝试检查文件是否存在:

var fs = require("fs");
console.log("Starting");

fs.exists("./sample.txt", function(fileok){
  if(fileok)fs.readFile("./sample.txt", function(error, data) {
    console.log("Contents: " + data);
  });
  else console.log("file not found");
});
console.log("Carry on executing");

如果它不存在,请检查路径、文件名和扩展名,因为您的代码是正确的。

3
根据您运行代码所在的位置,解析./sample.txt 的根路径可能会有所不同。
为了确保相对于您的模块进行解析,请执行以下操作:
var fs = require("fs");
var path = require('path');

var sampleTxt = path.join(__dirname, 'sample.txt');

console.log("Starting");
fs.readFile(sampleTxt, function(error, data) {
  if (error) return console.error(error);
  console.log("Contents: " + data);
});
console.log("Carry on executing");

1
即使文件存在,Node.js的fs.readFile()函数为什么总是返回undefined,只有在使用console.log(data)时才显示值。以下是示例:
    var content
    function myReadFile(filepath){
    fs.readFile(filepath,'utf8', function read(err, data) {
    if (err) {
      throw err;
    }
    content = data
    console.log(content); // Only this part of it returns the  value 
                          // not the content variable itself 
    })
    return content;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接