如何在NodeJs中读取文件到变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21963858/
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-09-02 16:54:59  来源:igfitidea点击:

How to read file to variable in NodeJs?

node.js

提问by Ryan Weir

i'm pretty new into NodeJs. And i am trying to read a file into a variable. Here is my code.

我对 NodeJs 很陌生。我正在尝试将文件读入变量。这是我的代码。

var fs = require("fs"),
    path = require("path"),
    util = require("util");
        var content;
        console.log(content);
        fs.readFile(path.join(__dirname,"helpers","test.txt"), 'utf8',function (err,data) {
            if (err) {
                console.log(err);
                process.exit(1);
            }
            content = util.format(data,"test","test","test");
        });
        console.log(content);

But every time i run the script i get undefinedand undefined

但每次我运行该脚本,我得到 undefinedundefined

What am i missing? Help please!

我错过了什么?请帮忙!

回答by Ryan Weir

As stated in the comments under your question, node is asynchronous - meaning that your function has not completed execution when your second console.logfunction is called.

正如您问题下的评论中所述,节点是异步的 - 这意味着当您的第二个console.log函数被调用时,您的函数尚未完成执行。

If you move the log statement inside the the callback after reading the file, you should see the contents outputted:

如果在读取文件后将 log 语句移动到回调中,您应该看到输出的内容:

var fs = require("fs"),
    path = require("path"),
    util = require("util");
var content;
console.log(content);
fs.readFile(path.join(__dirname, "helpers", "test.txt"), 'utf8', function (err, data) {
    if (err) {
        console.log(err);
        process.exit(1);
    }
    content = util.format(data, "test", "test", "test");
    console.log(content);
});

Even though this will solve your immediately problem, without an understanding of the async nature of node, you're going to encounter a lot of issues.

即使这会立即解决您的问题,但如果不了解节点的异步性质,您将遇到很多问题。

This similar stackoverflow answergoes into more details of what other alternatives are available.

这个类似的 stackoverflow 答案详细介绍了其他可用的替代方案。

回答by Zuhair Taha

or easily as follows:

或轻松如下:

const fs = require('fs');
const doAsync = require('doasync');

doAsync(fs).readFile('./file.txt')
    .then((data) => console.log(data));

回答by Abrar_11648

The following code snippet uses ReadStream. It reads your data in separated chunks, if your data file is small it will read the data in a single chunk. However this is a asynchronous task. So if you want to perform any task with your data, you need to include them within the ReadStream portion.

以下代码片段使用 ReadStream。它以分离的块读取您的数据,如果您的数据文件很小,它将读取单个块中的数据。然而,这是一个异步任务。因此,如果您想对数据执行任何任务,则需要将它们包含在 ReadStream 部分中。

var fs = require('fs');

var readStream = fs.createReadStream(__dirname + '/readMe.txt', 'utf8');
/* include the file directory and file name instead of <__dirname + '/readMe.txt'> */

var content;

readStream.on('data', function(chunk){
    content = chunk;
    performTask();
    
});

function performTask(){

    console.log(content);

}

There is also another easy way by using synchronous task. As this is a synchronous task, you do not need to worry about its executions. The program will only move to the next line after execution of the current line unlike the asynchronous task. A more clear and detailed answer is provided in the following link:

还有另一种简单的方法是使用同步任务。由于这是一个同步任务,您无需担心它的执行情况。与异步任务不同,程序只有在当前行执行后才会移动到下一行。以下链接提供了更清晰和详细的答案:

Get data from fs.readFile

从 fs.readFile 获取数据

var fs = require('fs');

var content = fs.readFileSync('readMe.txt','utf8');

/* include your file name instead of <'readMe.txt'> and make sure the file is in the same directory. */