Christopher Allen
Christopher Allen

Reputation: 8589

fs.readFile Function Response is undefined... Any Ideas?

Im running a simple readfile command, for a video tutorial, and this is the code exactly as the instructor saved it...

var fs = require("fs");
console.log("Starting");
fs.readFile("./sample.txt", function(error, data) {
console.log("Contents: " + data);
});
console.log("Carry on executing");

i have the sample.txt in the same folder as this js file, and in the sample.txt file i have "This is a sample output for this text document", unfortunately i get a "undefined" as the output for the data variable in the code.

If anybody has any insight as to why this is happening, it would be wonderful if someone would help....

THANKS

Upvotes: 4

Views: 11352

Answers (3)

Even when the file exists Why Does fs.readFile() function of Node.js always returns undefined only when console.log(data) is used it shows value. Example below

    var content
    function myReadFile(filepath){
    fs.readFile(filepath,'utf8', function read(err, data) {
    if (err) {
      throw err;
    }
    content = data
    console.log(content); // Only this part of it returns the  value 
                          // not the content variable itself 
    })
    return content;
    }

Upvotes: 1

Thorsten Lorenz
Thorsten Lorenz

Reputation: 11847

Depending on where you are running this from, the root at which ./sample.txt gets resolved may vary.

To ensure, that it resolves relative to your module, do the following:

var fs = require("fs");
var path = require('path');

var sampleTxt = path.join(__dirname, 'sample.txt');

console.log("Starting");
fs.readFile(sampleTxt, function(error, data) {
  if (error) return console.error(error);
  console.log("Contents: " + data);
});
console.log("Carry on executing");

Upvotes: 3

Riwels
Riwels

Reputation: 786

Try checking if the file exists first:

var fs = require("fs");
console.log("Starting");

fs.exists("./sample.txt", function(fileok){
  if(fileok)fs.readFile("./sample.txt", function(error, data) {
    console.log("Contents: " + data);
  });
  else console.log("file not found");
});
console.log("Carry on executing");

If it doesn't exists, check the path, filename and extension, because your code is OK.

Upvotes: 5

Related Questions