Last active
June 30, 2017 17:12
-
-
Save ccnokes/7d4f652638c245c40c00b69a083a3dd2 to your computer and use it in GitHub Desktop.
unix yes command in node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// throughput is usually ~350-400 MiB/s | |
// run: node yes.js | pv > /dev/null | |
const buf = Buffer.alloc(4096, 'y\n', 'utf8'); | |
const str = buf.toString(); | |
const { Readable } = require('stream'); | |
class Y extends Readable { | |
_read() { | |
this.push(str); | |
} | |
} | |
const stream = new Y(); | |
stream.pipe(process.stdout); | |
//--------------------------- | |
// Averages 2.25 GiB/s | |
// Based on https://www.reddit.com/r/unix/comments/6gxduc/how_is_gnu_yes_so_fast/diuibhe/ | |
const BUFSIZ = process.stdout._writableState.highWaterMark / 2; | |
const str = process.argv[2] || 'y'; | |
const len = str.length + 1; | |
const buffer = Buffer.from(Array.from({ length: BUFSIZ }, () => str).join('\n')); | |
function yes() { | |
// write accepts a callback function. while(true) will cause OOM crash | |
// so this is recursive | |
process.stdout.write(buffer, yes); | |
} | |
yes(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment