1

I have written a code for reading a file contents while i running it does not returns file contents but NAN. Below is my code:-

var fs = require('fs');

if (fs.existsSync('Temp')){
console.log('Directory exists, removing...');
if(fs.existsSync('Temp/new.txt')){
    fs.unlinkSync('Temp/new.txt');
}
fs.rmdirSync('Temp');
}

fs.mkdirSync('Temp');

console.log('running');

if(fs.existsSync('Temp')){
process.chdir('Temp');
fs.writeFileSync('test.txt', 'This is some test text for the file2');
fs.renameSync('test.txt', 'new.txt');
console.log('File has size:', + fs.statSync('new.txt').size + ' bytes');
console.log('File contents:', + fs.readFileSync('new.txt', {encoding: 'utf8'}));
}
Nitin Tayal
  • 59
  • 1
  • 9

1 Answers1

2

You're using the unary operator which converts anything to number instead of concatenating the output.

You either, remove the comma (,) from your console.log and use string concatenation, or remove the + and send the content as console.log second argument.

// I'm concatenating here
console.log('File contents:' + fs.readFileSync('new.txt', {encoding: 'utf8'}));
// I'm sending the content as second argument of console.log
console.log('File contents:', fs.readFileSync('new.txt', {encoding: 'utf8'}));

What you are doing, can be translated to this, which will return NaN unless new.txt content is a number.

console.log(
    'File contents:', 
    Number(fs.readFileSync('new.txt', {encoding: 'utf8'}))
);

console.log('File content: ', + 'new.txt content'); // NaN
console.log('File content: ', Number('new.txt content')); // NaN

console.log('File content: ', 'new.txt content'); // ok
console.log('File content: ' + 'new.txt content'); // ok
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
  • Thanks Marcos, this was helpful. I accidently committed the same mistake of using ',' and '+' together which was causing it to return Nan. – Azan Momin Mar 07 '21 at 13:20