简体   繁体   中英

Reading file with Node.js

I have a problem reading the stats of a file. I have this code:

var fs = require('fs');
process.stdin.setEncoding('utf8');

process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
   var stats =fs.statSync(chunk);
   length=stats.size;
   console.log(length);
 }
});

When I exec this code I get this error:

return binding.stat(pathModule._makeLong(path));
             ^
Error: ENOENT, no such file or directory 'hello.txt

But the problem is that "hello.txt" actually exists at the same directory¡ I have tried with other files and I always get the same error. Any ideas?

Thanks¡

The chunk read from the standard input contains a new line in the end, which was conflicting with your call to fs.statSync . Try this:

process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null && chunk !== '') {
   var stats = fs.statSync(chunk.trim()); // trim the input
   length=stats.size;
   console.log(length);
 }
});

Also note that the function will be constantly executed for as long as 'readable' events are triggered. You may wish to terminate the program at some point or anything like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM