Reputation: 61
I try to use Nodejs fs.read Method in Mac OS. However it doesn't work.. I use below source code
var fs = require('fs');
fs.open('helloworld.txt', 'r', function(err, fd) {
fs.fstat(fd, function(err, stats) {
var bufferSize=stats.size ,
chunkSize=512,
buffer=new Buffer(bufferSize),
bytesRead = 0;
while (bytesRead < bufferSize) {
if ((bytesRead + chunkSize) > bufferSize) {
chunkSize = (bufferSize - bytesRead);
}
fs.read(fd, buffer, bytesRead, chunkSize, bytesRead, testCallback);
bytesRead += chunkSize;
}
console.log(buffer.toString('utf8'));
});
fs.close(fd);
});
var testCallback = function(err, bytesRead, buffer){
console.log('err : ' + err);
};
Actually, I use some example in stackoverflow.
When I execute the source,
err : Error: EBADF, read
this err is returned.
However if I use readFile method, it works well.
fs.readFile('helloworld.txt', function (err, data) {
if (err) throw err;
console.log(data.toString('utf8'));
});
result is
Hello World!
Of course, it's same file.
Please, let me know what the problem is.
Thank you.
Upvotes: 6
Views: 2819
Reputation: 288
The error in the code is that you are currently using asynchronus functions in your application. Which simply means that before performing the first operation the other one starts in parallel i.e. fs.close()
closes your file before performing the operation. You can simple replace them with synchronus functions provided by the same fs
module from node.js.
Upvotes: 0
Reputation: 121
The difference is not int the functions you are using, but in the way you are using them.
All those fs.* functions you are using are asynchronous, that means they run in parallel. So, when you run fs.close, the others have not finished yet.
You should close it inside the fs.stat block:
var fs = require('fs');
fs.open('helloworld.txt', 'r', function(err, fd) {
fs.fstat(fd, function(err, stats) {
var bufferSize=stats.size ,
chunkSize=512,
buffer=new Buffer(bufferSize),
bytesRead = 0;
while (bytesRead < bufferSize) {
if ((bytesRead + chunkSize) > bufferSize) {
chunkSize = (bufferSize - bytesRead);
}
fs.read(fd, buffer, bytesRead, chunkSize, bytesRead, testCallback);
bytesRead += chunkSize;
}
console.log(buffer.toString('utf8'));
fs.close(fd);
});
});
var testCallback = function(err, bytesRead, buffer){
console.log('err : ' + err);
};
Upvotes: 3
Reputation: 2968
fs.read
and fs.fstat
are async functions.
And just after calling, fstat
, you are closing the file (fs.close(fd);
).
That could be the reason for this error.
Upvotes: 0