Last active
November 20, 2015 02:55
-
-
Save princebot/398193dda2094d7ae500 to your computer and use it in GitHub Desktop.
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
#!/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