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
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With