Skip to content

Instantly share code, notes, and snippets.

@odnarb
Created July 2, 2016 16:29
Show Gist options
  • Save odnarb/14f98e985d3ea229d2d7a056a7647023 to your computer and use it in GitHub Desktop.
Save odnarb/14f98e985d3ea229d2d7a056a7647023 to your computer and use it in GitHub Desktop.
//This is supposed to be an ACTION inside a sails.js controller.
stream_to_file: function(req, res) {
//WRITE TO FILE, CHUNKED TRANSFER
// console.log( "Processing chunk transfer!" );
var UUIDGenerator = require('node-uuid');
var filename = 'my-stream-' + UUIDGenerator.v4() + '.txt';
var fs = require('fs');
var fd = null;
var flags = 'w'; //see reference for flags https://nodejs.org/api/fs.html
fd = fs.openSync(sails.config.paths.tmp + "/uploads/" + filename, flags ); //sails.js specific code
req.on('data', function(chunk) {
//console.log( "Got a chunk!" );
//console.log("chunk length: " + chunk.toString().length);
var row = "";
var patchedChunk = '';
try {
if( req.session.chunkedItem == undefined || req.session.chunkedItem == null ) {
//nothing was saved in session earlier, just try to parse it.
row = chunk.toString();
} else {
// console.log("Patching saved chunk...");
patchedChunk = req.session.chunkedItem + chunk.toString();
row = patchedChunk.toString();
//clear out the saved chunk in the session object for later use if this was a complete JSON object
delete req.session.chunkedItem;
patchedChunk = '';
} //endif
if (fd) {
var bytesWritten = fs.writeSync(fd, row);
//console.log("wrote " + bytesWritten + " bytes");
} else {
return res.serverError();
}
} catch(e) {
// console.log("Chunk too long, trying to concatenate to one big string.")
//append to the string saved in the session object as there could be more chunks
if(req.session.chunkedItem == undefined) {
req.session.chunkedItem = chunk.toString();
} else {
req.session.chunkedItem = req.session.chunkedItem + chunk.toString();
}
//console.log(e);
} //end try/catch
});
req.on('end', function(){
// print the output in console
// console.log("chunk processing complete!");
fs.closeSync(fd);
return res.send(200);
});
}
}
@odnarb
Copy link
Author

odnarb commented Jul 2, 2016

@Sergey80 @r0hitsharma

Wanted to add you on this, since the original issue was closed.

request/request#401

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment