I am new to Node.js and trying to read a string from file along with data from file, console is printing 'undefined' as well. Whenever i comment out readFile function this error/warning goes away so i know for sure that i am doing something wrong while reading the file.
filehandeling.js
const fs = require('fs');
function writeIntoFile(str) {
fs.writeFile('./File.txt', str, function(err){
if (err){
console.log("Error occured");
// console.log(`Unable to write into file ${err}`);
}else{
console.log('Written into File');
}
});
}
function readFromFile() {
fs.readFile('File.txt', function (err, data) {
if (err) {
console.log(err);
}
console.log("Data read: " + data.toString());
});
}
module.exports.writeIntoFile = writeIntoFile;
module.exports.readFromFile = readFromFile;
app.js
const logger = require('./logger');
const fh = require('./filehandeling');
//var mysum = logger.sum(1,2);
fh.writeIntoFile(`Sum of Numbers is 4`);
console.log(fh.readFromFile());
// console.log(logger.sum(1,2));
Output:
PS D:\Dev\Node\FirstProject> node app.js
undefined
Written into File
Asynchronous read: Sum of Numbers is 4
PS D:\Dev\Node\FirstProject>