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.
open
's callback is kind of strange. – Rodi