Skip to content

Instantly share code, notes, and snippets.

@AdSegura
Last active October 24, 2019 18:08
Show Gist options
  • Save AdSegura/e61814290f5021f908983dafe0ba1cdb to your computer and use it in GitHub Desktop.
Save AdSegura/e61814290f5021f908983dafe0ba1cdb to your computer and use it in GitHub Desktop.
Nodejs workers as writeable stream
'use strict';
/**
* Nodejs Stream Workers example
* will cipher and return deciphered file.txt to console output
* using a worker as a writeable stream.
*
* Use:
* node boss.js < file.txt
*
* if node < 12
* node --experimental-worker boss.js < file.txt
*
* will cipher file.txt and return deciphered to console :)
*/
const { Worker } = require('worker_threads');
// stdin: true will make worker become a stream
const worker = new Worker('./worker.js', {stdin: true});
//pipe to worker
process.stdin.pipe(worker.stdin);
'use strict';
//all sync mode it's a worker it wont block the loop
const crypto = require('crypto');
const key = 'rxSy6ImrMS5hyPU6pg7x3aR4ILxNkuWITNCUe4QALQw=';
let iv = crypto.randomBytes(16);
const createCipheriv = (alg, key) => {
return crypto.createCipheriv(alg, Buffer.from(key, 'base64'), iv);
};
const createDecipherIv = (alg, key) => {
return crypto.createDecipheriv(alg, Buffer.from(key, 'base64'), iv);
};
process.stdin
.pipe(createCipheriv('aes-256-cbc', key))
.pipe(createDecipherIv('aes-256-cbc', key))
.pipe(process.stdout);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment