使用FS使用NodeJS读取.txt文件 [英] Reading a .txt file with NodeJS using FS

查看:324
本文介绍了使用FS使用NodeJS读取.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用NodeJS通过fs读取txt文件.这是app.js的代码:

I'm trying to use NodeJS to read a txt file by using fs. This is the code of app.js:

var fs = require('fs');

function read(file) {
    return fs.readFile(file, 'utf8', function(err, data) {
        if (err) {
            console.log(err);
        }
        return data;
    });
}

var output = read('file.txt');
console.log(output);

当我这样做时:

node app.js

undefined

我已经安装了fs,并且在同一目录中有一个file.txt,为什么它不起作用?

I have fs installed and there is a file.txt in the same directory, why is it not working?

推荐答案

您的read函数返回fs.readFile函数的结果,该结果为undefined,因为它没有return子句(它使用回调).您的第二个return子句位于匿名函数中,因此它仅返回该作用域.无论如何,您的函数在第一次返回后就知道其完成.

Your read function is returning the result of the fs.readFile function, which is undefined because it doesn't have a return clause (it uses callbacks). Your second return clause is in an anonymous function, so it only returns to that scope. Anyhow, your function knows its finished after that first return.

使用fs.readFile的标准方法是使用回调.

The standard way to use fs.readFile is to use callbacks.

var fs = require('fs');

function read(file, callback) {
    fs.readFile(file, 'utf8', function(err, data) {
        if (err) {
            console.log(err);
        }
        callback(data);
    });
}

var output = read('file.txt', function(data) {
    console.log(data);
});

这篇关于使用FS使用NodeJS读取.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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