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 文件中我有“这是此文本文档的示例输出”,不幸的是,我得到一个“未定义”作为数据变量的输出在代码中。

如果有人对为什么会发生这种情况有任何见解,如果有人能提供帮助,那就太好了......

谢谢

4

3 回答 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");

如果不存在,请检查路径、文件名和扩展名,因为您的代码没有问题。

于 2013-01-13T23:32:29.873 回答
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");
于 2013-01-14T05:39:01.193 回答
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;
    }
于 2017-08-19T21:24:50.057 回答