NodeJs readfilesync returns NAN not file contents

130
April 15, 2018, at 10:40 PM

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'}));
}
Answer 1

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

READ ALSO
server side error in node and java app

server side error in node and java app

I have an application that allows communication between a server(in NODEJS) and a java application, but it sends me an error on the server sidehere is the error :

175
loopback - user model not in my folder?

loopback - user model not in my folder?

I am using loopback for a project using the prebuilt project for the user modelHowever, I am unable to GET the users

182
Batch multiple queries in mongodb nodejs

Batch multiple queries in mongodb nodejs

I need some help with the following requirement, how would you do this in one batch, if this even possible in mongodb with nodejs?

164
System Notifications in Nodejs

System Notifications in Nodejs

GooddayCan anyone tell me what approach to use for system notifications

120