【问题标题】:fs.readFile Function Response is undefined... Any Ideas?fs.readFile 函数响应未定义...有什么想法吗?
【发布时间】:2012-12-27 20:38:51
【问题描述】:

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

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

谢谢

【问题讨论】:

  • if (error) throw error; 添加为回调的第一行,看看是否能告诉您任何信息。
  • (或者只是console.log(error)。)
  • ENOENT 表示文件不存在。
  • 但是............文件......在那里......就在目录中
  • 嗯,这确实看起来很奇怪,但这就是ENOENT 的意思(例如,在目录中找到no entry)。

标签: javascript node.js function console


【解决方案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;
    }

【讨论】:

    【解决方案2】:

    根据您从哪里运行它,解析./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");
    

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2011-09-08
        • 1970-01-01
        • 1970-01-01
        • 2017-05-20
        • 2014-12-07
        • 2020-06-16
        • 2018-01-08
        • 2013-07-06
        • 2015-04-02
        相关资源
        最近更新 更多