Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 376
Christopher Allen Avatar asked Jan 14 '23 12:01

Christopher Allen


2 Answers

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.

like image 170
Riwels Avatar answered Jan 22 '23 13:01

Riwels


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");
like image 24
Thorsten Lorenz Avatar answered Jan 22 '23 13:01

Thorsten Lorenz