3 ms·
I think there's an interesting inflection point between piping different utilities together to get something done, and just whipping up a script to do the same
by russellbeattie 6y ago
I think there's an interesting inflection point between piping different utilities together to get something done, and just whipping up a script to do the same thing instead.
First I'll use the command line to, say, grab a file from a URL, parse, sort and format it. If I find myself doing the same commands a lot, I'll make a .sh file and pop the commands in there.
But then there's that next step, which is where Bash in particular falls down: Branching and loops or any real logic. I've tried it enough times to know it's not worth it. So at this point, I load up a text editor and write a NodeJS script which does the same thing (Used to be Perl, or Python). If I need more functionality than what's in the standard library, I'll make a folder and do an npm init -y and npm install a few packages for what I need.
This is not as elegant as pipes, but I have more fine grained control over the data, and the end result is a folder I can zip and send to someone else in case they want to use the same script.
There is a way to make a NodeJS script listen to STDIO and act like another Unix utility, but I never do that. Once I'm in a scripting environment, I might as well just put it all in there so it's in one place.
- mongol 6y agoI have never come across a NodeJS script instead of a shell script. Can you suggest an example to look at that shows the advantages of this?
- falafel 6y agoThere are plenty of CLI tools built on Node: https://github.com/sindresorhus/awesome-nodejs#command-line-apps https://github.com/sindresorhus/awesome-nodejs#command-line-...
- russellbeattie 6y agoHere's a JS script [1] I wrote a little while ago just for my own use that queries the CDC for the latest virus numbers, then calcs the average, formats the data and prints to the command line. You can pass in a number of days, otherwise it pulls the last 14 days. $ node query-cdc.js 7 It's nothing special, but I wouldn't want to try to do this with command line utilities. (And yes, it was a bit uglier, but I cleaned it up of random crap I had thrown in before posting it.) 1. https://gist.github.com/russellbeattie/f9edf91115b43d6d7ca3cf0b4f9eb060 https://gist.github.com/russellbeattie/f9edf91115b43d6d7ca3c...
- mongol 6y agoThanks, appreciated! I guess using shebang #!/usr/bin/node does not work as # is not a valid comment?
- russellbeattie 6y agoI think Node has an exception for that built in, so you can do that or #!/usr/bin/env node and it'll work.
- devit 6y agoBash has perfectly functional if, while and for constructs.