15

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

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

What am i missing? Help please!

6
  • 1
    fs.readFile is asynchronous (which is why you use a callback). Either do everything from the callback or use var content = fs.readFileSync("filename") Commented Feb 23, 2014 at 3:35
  • 3
    Welcome to the wonderful world of async! You can't do that. Commented Feb 23, 2014 at 3:36
  • It returns a Buffer. How to convert Buffer to String? Commented Feb 23, 2014 at 3:41
  • Possible duplicate of Get data from fs.readFile Commented Jul 12, 2016 at 13:55
  • duplicate of stackoverflow.com/questions/10058814/get-data-from-fs-readfile Commented Jul 12, 2016 at 13:55

4 Answers 4

11

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.

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.

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

Sign up to request clarification or add additional context in comments.

Comments

11

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.

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

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. */

Comments

6

or easily as follows:

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

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

Comments

1

One very simple way:

var json = require("./file.json");
console.log(JSON.stringify(json 4, true));

Comments

Your Answer

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