Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript fs.readFile函数响应未定义。。。有什么想法吗?_Javascript_Node.js_Function_Console - Fatal编程技术网

Javascript fs.readFile函数响应未定义。。。有什么想法吗?

Javascript fs.readFile函数响应未定义。。。有什么想法吗?,javascript,node.js,function,console,Javascript,Node.js,Function,Console,我正在运行一个简单的readfile命令,用于视频教程,这是讲师保存的代码 var fs = require("fs"); console.log("Starting"); fs.readFile("./sample.txt", function(error, data) { console.log("Contents: " + data); }); console.log("Carry on executing"); 我的sample.txt与这个js文件在同一个文件夹中, 在sample.

我正在运行一个简单的readfile命令,用于视频教程,这是讲师保存的代码

var fs = require("fs");
console.log("Starting");
fs.readFile("./sample.txt", function(error, data) {
console.log("Contents: " + data);
});
console.log("Carry on executing");
我的sample.txt与这个js文件在同一个文件夹中, 在sample.txt文件中,我有“这是这个文本文档的示例输出”, 不幸的是,我得到了一个“未定义”作为代码中数据变量的输出

如果有人知道为什么会发生这种情况,如果有人能帮上忙,那就太好了


谢谢

请先检查文件是否存在:

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");

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

根据您运行它的位置,解析
/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");

即使文件存在,为什么Node.js的fs.readFile()函数总是返回undefined,只有在使用console.log(数据)时才会显示值。下面的例子

    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;
    }

添加
if(error)抛出错误
作为回调的第一行,看看这是否告诉您任何事情。(或者只是
console.log(error)
enoint
表示文件不在那里。但是。。。。。。。。。。档案。。。。有。。。。。。就在目录中,这确实看起来很奇怪,但这就是
enoint
的意思(比如,
no-ent
ry在目录中找到)。