Javascript 从 fs.readFile 获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10058814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:40:29  来源:igfitidea点击:

Get data from fs.readFile

javascriptnode.js

提问by karaxuna

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

Logs undefined, why?

日志undefined,为什么?

回答by Matt Esch

To elaborate on what @Raynos said, the function you have defined is an asynchronous callback. It doesn't execute right away, rather it executes when the file loading has completed. When you call readFile, control is returned immediately and the next line of code is executed. So when you call console.log, your callback has not yet been invoked, and this content has not yet been set. Welcome to asynchronous programming.

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

Example approaches

示例方法

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

Or better yet, as Raynos example shows, wrap your call in a function and pass in your own callbacks. (Apparently this is better practice) I think getting into the habit of wrapping your async calls in function that takes a callback will save you a lot of trouble and messy code.

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

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

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

回答by Logan

There is actually a Synchronous function for this:

实际上有一个同步功能:

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

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

Asynchronous

异步

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

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

Asynchronously reads the entire contents of a file. Example:

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

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

The callback is passed two arguments (err, data), where data is the contents of the file.

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

If no encoding is specified, then the raw buffer is returned.

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



SYNCHRONOUS

同步

fs.readFileSync(filename, [encoding])

fs.readFileSync(filename, [encoding])

Synchronous version of fs.readFile. Returns the contents of the file named filename.

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

If encoding is specified then this function returns a string. Otherwise it returns a buffer.

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

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

回答by Raynos

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

回答by Evan Carroll

Using Promises with ES7

在 ES7 中使用 Promise

Asynchronous use with mz/fs

与 mz/fs 异步使用

The mzmodule provides promisified versions of the core node library. Using them is simple. First install the library...

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

npm install mz

Then...

然后...

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

Alternatively you can write them in asynchronous functions:

或者,您可以在异步函数中编写它们:

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

回答by user2266928

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

use this for calling a file synchronously, without encoding its showing output as a buffer.

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

回答by Aravin

This line will work,

这条线会起作用,

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

回答by doctorlee

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

回答by Zeeshan Hassan Memon

sync and async file reading way:

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

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

Node Cheat Available at read_file.

节点作弊 在read_file可用。

回答by Taitu-lism

As said, fs.readFileis an asynchronous action. It means that when you tell node to read a file, you need to consider that it will take some time, and in the meantime, node continued to run the following code. In your case it's: console.log(content);.

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

It's like sending some part of your code for a long trip (like reading a big file).

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

Take a look at the comments that I've written:

看看我写的评论:

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

That's why contentis still empty when you log it. node has not yet retrieved the file's content.

这就是为什么content在您登录时仍然为空的原因。节点尚未检索文件的内容。

This could be resolved by moving console.log(content)inside the callback function, right after content = data;. This way you will see the log when node is done reading the file and after contentgets a value.

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

回答by Dominic

Use the built in promisify library (Node 8+) to make these old callback functions more elegant.

使用内置的 promisify 库(Node 8+)使这些旧的回调函数更加优雅。

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