Skip to content

Instantly share code, notes, and snippets.

@karlpokus
Created October 30, 2016 13:18
Show Gist options
  • Save karlpokus/2591d6c20444f1ee9769020f60477998 to your computer and use it in GitHub Desktop.
Save karlpokus/2591d6c20444f1ee9769020f60477998 to your computer and use it in GitHub Desktop.
pipe to js. Pipe from file, echo or just pass some args
#!/usr/bin/env node
// 1. add shebang above
// 2. make file executable
// $ chmod +x pipeToMe.js
// 3. pipe from file
// $ cat file | ./pipeToMe.js
// 4. pipe from echo
// $ echo -n one two | ./pipeToMe.js
// 5. just pass some args
// $ ./pipeToMe.js one two
function parsePipedData() {
var data = '',
out;
process.stdin
.on('data', function(chunk) {
data += chunk;
})
.on('end', function() {
if (/\n/.test(data)) { // split by EOL
out = data
.trim()
.split('\n')
.filter(function(item){ // filter empty strings
return item;
});
console.log(out);
} else if (/\s/.test(data)) { // split by space
console.log(data.trim().split(' '));
} else {
console.log('nothing found');
}
});
}
function parseShellArgs() {
console.log(process.argv.slice(2));
}
if (process.stdin.isTTY) {
parseShellArgs();
} else {
parsePipedData();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment