从 fs.readFile 获取数据

Get data from fs.readFile

本文关键字:数据 获取 readFile fs      更新时间:2023-09-26
var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

日志undefined,为什么?

为了详细说明@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(filename, [encoding], [callback])

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

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

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

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

<小时 />

同步

fs.readFileSync(filename, [encoding])

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

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

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

在 ES7 中使用承诺

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

这一行将起作用,

const content = fs.readFileSync('./Index.html', 'utf8');
console.log(content);
var data = fs.readFileSync('tmp/reltioconfig.json','utf8');

使用它来同步调用文件,无需将其显示输出编码为缓冲区。

如前所述,fs.readFile是一个异步操作。这意味着当你告诉node读取一个文件时,你需要考虑这将需要一些时间,同时,node继续运行下面的代码。在您的情况下是:console.log(content); .

这就像发送部分代码进行长途旅行(例如读取大文件)。

看看我写的评论:

var content;
// node, go fetch this file. when you come back, please run this "read" callback function
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
// in the meantime, please continue and run this console.log
console.log(content);

这就是为什么content在你记录它时它仍然是空的。 节点尚未检索文件的内容。

这可以通过在回调函数内移动console.log(content)来解决,紧接着content = data;。这样,当节点读取完文件并在content获取值后,您将看到日志。

来自节点 v8

使用内置的 promisify 库使这些旧的回调函数更加优雅。

const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);
async function doStuff() {
  try {
    const content = await readFile(filePath, 'utf8');
    console.log(content);
  } catch (e) {
    console.error(e);
  }
}

从节点 v10

您可以使用 fs API 的承诺版本:

import { promises as fs } from 'fs';
async function doStuff() {
  try {
    const content = await fs.readFile(filePath, 'utf8');
    console.log(content);
  } catch (e) {
    console.error(e);
  }
}
const fs = require('fs')
function readDemo1(file1) {
    return new Promise(function (resolve, reject) {
        fs.readFile(file1, 'utf8', function (err, dataDemo1) {
            if (err)
                reject(err);
            else
                resolve(dataDemo1);
        });
    });
}
async function copyFile() {
    try {
        let dataDemo1 = await readDemo1('url')
        dataDemo1 += ''n' +  await readDemo1('url')
        await writeDemo2(dataDemo1)
        console.log(dataDemo1)
    } catch (error) {
        console.error(error);
    }
}
copyFile();
function writeDemo2(dataDemo1) {
    return new Promise(function(resolve, reject) {
      fs.writeFile('text.txt', dataDemo1, 'utf8', function(err) {
        if (err)
          reject(err);
        else
          resolve("Promise Success!");
      });
    });
  }

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

//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 path = "index.html"
const readFileAsync = fs.readFileSync(path, 'utf8');
// console.log(readFileAsync)

使用简单的readFileSync对我有用。

var fs = require('fs');
var path = (process.cwd()+"''text.txt");
fs.readFile(path , function(err,data)
{
    if(err)
        console.log(err)
    else
        console.log(data.toString());
});
var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

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

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.
})
以下是适用于

async包装或承诺then链的函数

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

粗略地说,你正在处理node.js它本质上是异步的。

当我们谈论异步时,我们谈论的是处理其他事情时执行或处理信息或数据。它不是并行的同义词,请注意。

您的代码:

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

对于您的示例,它基本上首先执行控制台.log部分,因此变量"内容"未定义。

如果您确实想要输出,请改为执行以下操作:

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

这是异步的。很难习惯,但事实就是如此。同样,这是对异步是什么的粗略但快速的解释。

我喜欢使用

fs-extra,因为所有函数都是有前途的,开箱即用,所以你可以使用 await .因此,您的代码可能如下所示:

(async () => {
   try {
      const content = await fs.readFile('./Index.html');
      console.log(content);
   } catch (err) {
      console.error(err);
   }
})();