Andrew Luhring
Andrew Luhring

Reputation: 1914

How do I create a globally usable shell script using Nodejs rather than bash?

Basically, I want to be able to open a terminal and type

$ haylp

and have that return some helpful commands that I keep forgetting. I wanna do this without having to learn bash. or some other language because I know JavaScript. How can I do this without having to compile it or translate it into bash or anything? I just want to write a javascript file and have it run as if i wrote a shell script and put it in /usr/local/bin.

Upvotes: 0

Views: 672

Answers (1)

Andrew Luhring
Andrew Luhring

Reputation: 1914

I figured it out and I just want people to know how to do it.

First, simple example- I wrote the text file I wanted to reference. Just a normal text or markdown file. I called it haylp.md

haylp.md:

commands i keep forgetting

Then I created a Node/JavaScript file called haylp.js to read the contents of it:

haylp.js

const fs = require('fs');

fs.readFile('/usr/local/lib/haylp/emacsCmds.md', 'utf8', (err, data) =>{
    if(err){ console.error(err); return; }
    console.log(data);    
});

and this is where I got confused because I KNOW there's a way to just use a shebang that looks like "#!/bin/node" that would allow you to just type

$ haylp (or) ./haylp.js (or) sh ./haylp.js

So this answered my question about the shebang but I still couldnt get it to execute and also didn't know where to put it. So here's the full result.

Step 1 create the js file and add the 2 line shebang for compatibility.

haylp.js:

#!/bin/sh
':' //; exec "$(command -v nodejs || command -v node)" "$0" "$@"


const fs = require('fs');

fs.readFile('/usr/local/lib/haylp/emacsCmds.md', 'utf8', (err, data) =>{
    if(err){ console.error(err); return; }
    console.log(data);    
});

Step 2 Create the text file

Place it in a folder in /usr/local/lib/haylp (I'm not positive if this is the right place to put it; someone correct me if i'm wrong)

Step 3 Make the js file executable:

$ chmod +x haylp.js

Step 4 Copy haylp.js to bin

$ sudo mv ./haylp.js /usr/local/bin/haylp

Is this overkill for my usecase? Probably. But it might not be for yours. It's probably not perfect so if anyone has suggestions, I'm all ears.

Upvotes: 1

Related Questions