Reading a .txt file with NodeJS using FS

▼魔方 西西 提交于 2019-12-12 01:25:28

问题


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

When i do:

node app.js

It says

undefined

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


回答1:


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.

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


来源:https://stackoverflow.com/questions/29577774/reading-a-txt-file-with-nodejs-using-fs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!