0

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> 

1 Answers1

0

It prints undefined because you are actually printing the return value of the function readFromFile, which does not return anything. Your code can read your file as it prints Sum of Numbers is 4 correctly in your readFromFile function.

function readFromFile() {

fs.readFile('File.txt', function (err, data) {
    if (err) {
       console.log(err);
    }
    console.log("Data read: " + data.toString());
    ^^^^^^^^^^^^^
    you are printing the correct content of your file here
 }); 
}

If you want to return the content of the file consider the synchronous counterpart of fs.readFile which is fs.readFileSync https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options. Then you could do

function readFromFile() {
    return fs.readFileSync('File.txt', 'utf-8');
}

and your code doesn't print undefined anymore.

Additionally, your code has a typo: const fh = require('./filehandeling'); has to be const fh = require('./filehandling');


EDIT:

It's true that the synchronous readFile doesn't work right now. The problem is that writeFile is still asynchronous and never gets to actually write to the file. There are several possibilities how to resolve this. Two of them is switching to synchronously writing the file or to give the asynchronous version a callback.

Synchronous write

filehandling.js

const fs = require('fs');

function writeIntoFile(str) {
    fs.writeFileSync('./File.txt', str);
}

function readFromFile() {
    return fs.readFileSync('File.txt', 'utf-8');
}

module.exports.writeIntoFile = writeIntoFile;
module.exports.readFromFile = readFromFile;

app.js

const fh = require('./filehandling');

fh.writeIntoFile(`Sum of Numbers is 4`);
console.log(fh.readFromFile());

Callback

filehandling.js

const fs = require('fs');

function writeIntoFile(str, callback) {
    fs.writeFile('./File.txt', str, callback);
}

function readFromFile() {
    return fs.readFileSync('File.txt', 'utf-8');
}

module.exports.writeIntoFile = writeIntoFile;
module.exports.readFromFile = readFromFile;

app.js

const fh = require('./filehandling');

fh.writeIntoFile(`Sum of Numbers is 4`, err => {
    if (err) {
        throw err;
    }
    console.log(fh.readFromFile());
});
steven.westside
  • 259
  • 2
  • 8