Skip to content

Instantly share code, notes, and snippets.

@princebot
Last active November 20, 2015 02:55
Show Gist options
  • Save princebot/398193dda2094d7ae500 to your computer and use it in GitHub Desktop.
Save princebot/398193dda2094d7ae500 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
/* GNU utility `cat` as a JavaScript executable.
*
* This works mostly the same as `cat`, with one difference: an explicit
* argument of '-' (specifying stdin) is processed _after_ all filename
* arguments.
*
* USAGE: cat.js [<FILE> <FILE...> [-]]
*/
'use strict';
let fs = require('fs');
function readStdin() {
process.stdin.on('readable', function() {
let chunk = process.stdin.read();
if (chunk !== null) {
process.stdout.write(chunk);
}
});
}
if (!process.argv.slice(2).length) {
readStdin();
}
process.argv.forEach(function(file, index) {
if (index < 2) {
return;
}
if (file == '-') {
readStdin();
return;
}
fs.readFile(file, 'utf8', function(error, data) {
if (error) {
throw new Error(
`File "${file}" does not exist or is not readable`
);
}
console.log(data);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment