如何在NodeJs中读取文件到变量? [英] How to read file to variable in NodeJs?

查看:44
本文介绍了如何在NodeJs中读取文件到变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

但是每次我运行脚本时我都会得到undefinedundefined

But every time i run the script i get undefined and undefined

我错过了什么?请帮忙!

What am i missing? Help please!

推荐答案

如您问题下的评论所述,node 是异步的 - 这意味着您的函数在您的第二个 console.log 函数被调用.

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

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

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

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.

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

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

这篇关于如何在NodeJs中读取文件到变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆