我找到了一种可行的方法,但可能不是理想的方法。
flow.write
在这里,我正在调用flow.post
if status
is done
and currentTestChunk > numberOfChunks
。我会进行大于检查,因为有时会flow.post
发送status done
不止一次,如此处所述。
编辑:我添加了一种在创建文件后清理块的方法。
flow.post(req, function(status, filename, original_filename, identifier, currentTestChunk, numberOfChunks) {
console.log('POST', status, original_filename, identifier);
res.send(200);
if (status === 'done' && currentTestChunk > numberOfChunks) {
var stream = fs.createWriteStream('./tmp/' + filename);
//EDIT: I removed options {end: true} because it isn't needed
//and added {onDone: flow.clean} to remove the chunks after writing
//the file.
flow.write(identifier, stream, { onDone: flow.clean });
}
})
我不得不修改flow.post
's 的回调来发送currentTestChunk
和numberOfChunks
.
文件:flow-node.js
$.post = function(req, callback){
//There's some codez here that we can overlook...
fs.rename(files[$.fileParameterName].path, chunkFilename, function(){
// Do we have all the chunks?
var currentTestChunk = 1;
var numberOfChunks = Math.max(Math.floor(totalSize/(chunkSize*1.0)), 1);
var testChunkExists = function(){
fs.exists(getChunkFilename(currentTestChunk, identifier), function(exists){
if(exists){
currentTestChunk++;
if(currentTestChunk>numberOfChunks) {
//Add currentTestChunk and numberOfChunks to the callback
callback('done', filename, original_filename, identifier, currentTestChunk, numberOfChunks);
} else {
// Recursion
testChunkExists();
}
} else {
//Add currentTestChunk and numberOfChunks to the callback
callback('partly_done', filename, original_filename, identifier, currentTestChunk, numberOfChunks);
}
});
}
testChunkExists();
});
} else {
callback(validation, filename, original_filename, identifier);
}
}
如果要删除块,请在 flow.write 中使用 onDone 调用 flow.clean。
$.write = function(identifier, writableStream, options) {
options = options || {};
options.end = (typeof options['end'] == 'undefined' ? true : options['end']);
// Iterate over each chunk
var pipeChunk = function(number) {
var chunkFilename = getChunkFilename(number, identifier);
fs.exists(chunkFilename, function(exists) {
if (exists) {
// If the chunk with the current number exists,
// then create a ReadStream from the file
// and pipe it to the specified writableStream.
var sourceStream = fs.createReadStream(chunkFilename);
sourceStream.pipe(writableStream, {
end: false
});
sourceStream.on('end', function() {
// When the chunk is fully streamed,
// jump to the next one
pipeChunk(number + 1);
});
} else {
// When all the chunks have been piped, end the stream
if (options.end) {
writableStream.end();
}
//Options.onDone contains flow.clean so here I'm deleting all the chunked files.
if (options.onDone) {
options.onDone(identifier);
}
}
});
}
pipeChunk(1);
}