我编写了一个用于读取文件内容的代码,而我运行它时不会返回文件内容而是NAN。以下是我的代码: -
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'}));
}
答案 0 :(得分:1)
您正在使用unary operator将任何内容转换为数字而不是连接输出。
您要么从您的,
中删除逗号(console.log
)并使用字符串连接,要么删除+
并将内容作为console.log
第二个参数发送。< / p>
// 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'}));
您正在做的事情可以转换为此内容,除非NaN
内容为数字,否则会返回new.txt
。
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