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

日志未定义,为什么?


当前回答

这条线可以,

const content = fs.readFileSync('./Index.html', 'utf8');
console.log(content);

其他回答

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

同步和异步文件读取方式:

//fs module to read file in sync and async way

var fs = require('fs'),
    filePath = './sample_files/sample_css.css';

// this for async way
/*fs.readFile(filePath, 'utf8', function (err, data) {
    if (err) throw err;
    console.log(data);
});*/

//this is sync way
var css = fs.readFileSync(filePath, 'utf8');
console.log(css);

节点欺骗可在read_file。

var data = fs.readFileSync('tmp/reltioconfig.json','utf8');

使用这个来同步调用一个文件, 不进行编码,将输出显示为缓冲区。

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

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

你可以读取文件

var readMyFile = function(path, cb) {
      fs.readFile(path, 'utf8', function(err, content) {
        if (err) return cb(err, null);
        cb(null, content);
      });
    };

加上你可以写入文件,

var createMyFile = (path, data, cb) => {
  fs.writeFile(path, data, function(err) {
    if (err) return console.error(err);
    cb();
  });
};

甚至连在一起

var readFileAndConvertToSentence = function(path, callback) {
  readMyFile(path, function(err, content) {
    if (err) {
      callback(err, null);
    } else {
      var sentence = content.split('\n').join(' ');
      callback(null, sentence);
    }
  });
};