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

日志未定义,为什么?


当前回答

这里实际上有一个同步函数:

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

异步

fs。readFile(filename, [encoding], [callback])

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

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

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

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


同步

fs。readFileSync(文件名,(编码))

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

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

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

其他回答

这条线可以,

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

这只是因为节点是异步的,它不会等待读取函数,一旦程序启动,它将控制台的值为未定义,这实际上是真的,因为没有值分配给内容变量。 我们可以使用承诺、生成器等来处理。 我们可以这样使用承诺。

new Promise((resolve,reject)=>{
    fs.readFile('./index.html','utf-8',(err, data)=>{
        if (err) {
            reject(err); // in the case of error, control flow goes to the catch block with the error occured.
        }
        else{
            resolve(data);  // in the case of success, control flow goes to the then block with the content of the file.
        }
    });
})
.then((data)=>{
    console.log(data); // use your content of the file here (in this then).    
})
.catch((err)=>{
    throw err; //  handle error here.
})

在ES7中使用Promises

与mz/fs异步使用

mz模块提供了核心节点库的承诺版本。使用它们很简单。首先安装库…

npm install mz

然后……

const fs = require('mz/fs');
fs.readFile('./Index.html').then(contents => console.log(contents))
  .catch(err => console.error(err));

或者你也可以在异步函数中写它们:

async function myReadfile () {
  try {
    const file = await fs.readFile('./Index.html');
  }
  catch (err) { console.error( err ) }
};

这里实际上有一个同步函数:

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

异步

fs。readFile(filename, [encoding], [callback])

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

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

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

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


同步

fs。readFileSync(文件名,(编码))

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

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

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

下面是函数将工作异步包装或承诺然后链

const readFileAsync =  async (path) => fs.readFileSync(path, 'utf8');