Reputation: 138
When client posts a chunk data(part of file), then server side should insert the chunk to file. But fs.open will truncate the file. So I cant use empty fd to write. Now this is what I am using it reads all buffer and changes the chunk range value in the buffer.
//badly code
fs.open(getFilePath(fileId),"r+",function(err,fd){
var bytes = new Buffer(metadata.fileSize);
fs.read(fd,bytes,0,bytes.length,0,function(){
for(var i=0;i<bytes.length;i++){
if(i>=start && i <= end){
bytes[i] = buffer[i-start];
}
}
//console.log(bytes);
fs.write(fd,bytes,0,bytes.length,0,function(err){
if(err) throw err;
fs.close(fd,function(){
metadata.addChunk(start,end);
metadata.save(callback);
});
});
});
});
Is there a better method to do this? Please tell me,thank you very much.
Upvotes: 2
Views: 8997
Reputation: 3011
I know this question might be a bit outdated but I faced the same problem, while trying to get source code to a file To solve this I did not use write file but append, for example:
res.on('data', function (chunk) {
fs.appendFile('body.txt', chunk, function (err) {
if(err) throw err;
});
This worked pretty fine for me
Upvotes: 5
Reputation: 17319
Sounds like you want to append http requests to a file.
Open an appending write stream.
var writeStream = fs.createWriteStream(path, {flags: 'a'});
Then in your http handler
function (req, res) {
req.pipe(writeStream, {end: false});
req.on('end', function () {
res.end('chunk received');
});
};
Upvotes: 3