13

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!

  • 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")` – Blender Feb 23 '14 at 03:35
  • 3
    Welcome to the wonderful world of **async**! You can't do that. – SLaks Feb 23 '14 at 03:36
  • It returns a Buffer. How to convert Buffer to String? –  Feb 23 '14 at 03:41
  • Possible duplicate of [Get data from fs.readFile](http://stackoverflow.com/questions/10058814/get-data-from-fs-readfile) – rofrol Jul 12 '16 at 13:55
  • duplicate of http://stackoverflow.com/questions/10058814/get-data-from-fs-readfile – rofrol Jul 12 '16 at 13:55
  • @user2540315 add 'utf8' after the filepath to make it not read buffer text – wongz Apr 09 '20 at 02:53

4 Answers4

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.

Harm
  • 590
  • 3
  • 21
Ryan Weir
  • 6,377
  • 5
  • 40
  • 60
9

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. */
Abrar_11648
  • 368
  • 4
  • 7
6

or easily as follows:

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

doAsync(fs).readFile('./file.txt')
    .then((data) => console.log(data));
Zuhair Taha
  • 2,808
  • 2
  • 35
  • 33
0

One very simple way:

var json = require("./file.json");
console.log(JSON.stringify(json 4, true));
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223