lokesh_bsr
lokesh_bsr

Reputation: 1

Node.js While run this small js file it gives the following error

var fs=require('fs');
fs.readFile('input.txt',function(err,data){
    if(err) 
        console.log(err);
    console.log(data.toString());
});
console.log('Program ended');

node nblock.js

*****gives following error******

TypeError: Cannot read property 'toString' of undefined
  at ReadFileContext.callback (C:\projects\text\nblock.js:5:19)
  at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:420:13)

Upvotes: 0

Views: 107

Answers (2)

Florian Suess
Florian Suess

Reputation: 765

So the program works for me when I have the text file 'input.txt' in the same directory as the program itself. You probably don't have this file in the same directory, you could add;

var fs = require('fs');
fs.readFile('input.txt', function(err, data) {
  if (!data) { // Check if we have retrieved any data
    console.log('There is no file, ', err);
    return;
  }

  console.log(data.toString());
});
console.log('Program ended');

This actually checks if there is anything before attempted to run the toString() method on a potentially undefined variable data.

Upvotes: 0

michaelitoh
michaelitoh

Reputation: 2340

In order to avoid the error try to return if there is an error and in this way the lines after the if statement wont be executed.

var fs=require('fs');
fs.readFile('input.txt',function(err,data){
    if(err) 
        return console.log(err);
    console.log(data.toString());
});
console.log('Program ended');

Upvotes: 1

Related Questions