2

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 Answer 1

4

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.