Skip to content

Instantly share code, notes, and snippets.

@deostroll
Last active June 1, 2016 11:14
Show Gist options
  • Select an option

  • Save deostroll/1059b394896154402981269592bf0c33 to your computer and use it in GitHub Desktop.

Select an option

Save deostroll/1059b394896154402981269592bf0c33 to your computer and use it in GitHub Desktop.
upload concat response

Express web app that exposes and upload endpoint.

Upload three files to it. Post successful upload of 3rd file a response is returned to each client

use cURL as client, but not mandatory.

var Readable = require('stream').Readable;
var fs = require('fs');
var spawn = require('child_process').spawn;
var express = require('express');
var multer = require('multer');
var app = express();
var uploading = multer({});
var files;
var done = false;
app.post('/upload', uploading.single('file'), (req, res) => {
var readable;
var push = (item) => {
readable.push(item.buffer);
readable.push(new Date().toString() + '\r\n')
};
var data;
if (!files) {
files = [];
}
// console.log(req.file);
files.push(req.file);
if (files.length === 3) {
readable = new Readable;
files.forEach(push);
readable.push(null);
var echo = spawn('node', ['index.js']);
echo.stdout.setEncoding('utf8');
echo.stdout.on('readable', () => {
var whole = echo.stdout.read();
if (whole) {
data = whole;
var json = new Readable;
json.push(data);
json.push(null);
json.pipe(fs.createWriteStream('combined-foo.txt'))
.on('close', () => {
done = true;
fs.createReadStream('combined-foo.txt').pipe(res);
});
}
});
readable
.pipe(echo.stdin);
files = undefined;
}
else {
var tmr = setInterval(() => {
if (done) {
clearInterval(tmr);
fs.createReadStream('combined-foo.txt').pipe(res);
}
}, 100);
}
});
app.listen('8000', (err) => {
if(!err) {
console.log('listening on port 8000');
}
});
//deleting the resultant file if it exists... (on restarting)
fs.exists('combined-foo.txt', (exists) => {
if (exists) {
fs.unlink('combined-foo.txt');
}
});
const fs = require('fs');
var rl = require('readline');
var stdinput = rl.createInterface({
input: process.stdin
});
var lines = []
stdinput.on('line', function(line) {
lines.push(line);
});
stdinput.on('close', () => {
console.log(JSON.stringify(lines));
});
{
"name": "nodejs-console-app1",
"version": "0.0.0",
"description": "NodejsConsoleApp1",
"main": "app.js",
"author": {
"name": "Arun_Jayapal",
"email": ""
},
"dependencies": {
"body-parser": "^1.15.1",
"express": "^4.13.4",
"multer": "^1.1.0",
"stream-multiplexer": "^1.0.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment