提问者:小点点

从fs.readFile中获取数据[重复]


var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

日志未定义,为什么?


共3个答案

匿名用户

为了详细说明@Raynos所说的内容,您定义的函数是一个异步回调。它不会立即执行,而是在文件加载完成后执行。调用 readFile 时,将立即返回控制权并执行下一行代码。所以当你调用 console.log 时,你的回调还没有被调用,这个内容还没有设置好。欢迎使用异步编程。

示例方法

const fs = require('fs');
// First I want to read the file
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    const content = data;

    // Invoke the next step here however you like
    console.log(content);   // Put all of the code here (not the best solution)
    processFile(content);   // Or put the next step in a function and invoke it
});

function processFile(content) {
    console.log(content);
}

或者更好的是,正如Raynos的例子所示,将您的调用包装在一个函数中并传递您自己的回调。(显然这是更好的做法)我认为养成将异步调用包装在接受回调的函数中的习惯会为您节省很多麻烦和混乱的代码。

function doSomething (callback) {
    // any async callback invokes callback with response
}

doSomething (function doSomethingAfter(err, result) {
    // process the async result
});

匿名用户

这实际上有一个同步功能:

http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_encoding

fs. readFile(文件名,[编码],[回调])

异步读取文件的全部内容。例子:

fs.readFile('/etc/passwd', function (err, data) {
  if (err) throw err;
  console.log(data);
});

回调传递两个参数(err,data),其中数据是文件的内容。

如果没有指定编码,则返回原始缓冲区。

fs.readFileSync(文件名, [编码])

fs. readFile的同步版本。返回名为filename的文件的内容。

如果指定了编码,则此函数将返回一个字符串。否则,它将返回一个缓冲区。

var text = fs.readFileSync('test.md','utf8')
console.log (text)

匿名用户

function readContent(callback) {
    fs.readFile("./Index.html", function (err, content) {
        if (err) return callback(err)
        callback(null, content)
    })
}

readContent(function (err, content) {
    console.log(content)
})