Global NPM/Node.js executables

nairihar
3 min readApr 6, 2023

Have you ever come across a library that, upon global installation, offers a range of global commands?

This is the popular eslint library. If you install it globally then you will get a global command called eslint.

Let’s see how to make something like that.

So, I write this piece of code into a file called hello.js.

#!/usr/bin/env node

console.log('Hey dear!');

Please take into consideration the first line. With that, we tell the Linux that whenever we try to execute this file then please use node as an executor.

Now if we try to execute our hello.js file, we will get this kind of error.

$ ./hello.js
-bash: ./hello.js: Permission denied

We forgot to make the file executable. To do so, we need to change its permissions.

For that, we need use chmod to make it work.

chmod +x hello.js

The +x option adds the execute permission on the file, and allows it to be run as a program.

Now we can run it like this!

$ ./hello.js
Hey dear!

Wow, congratulations on your first Node.js executable.

Btw we can simplify it more by renaming it into something like hello.
The file type isn’t important in this case, as we wrote something magical in the file’s first line.

I will not try that, as we wanted something which will be played with npm i -g, right?

So let’s continue cooking…

We can check eslint's code base, and see how they did that. We just need to check their package.json file.

https://github.com/eslint/eslint/blob/main/package.json

As you can see here they have used this bin object to configure their global executable command.

Now I’m going to do the same.

I will create a Node.js project. And configure the hello.js executable like in eslint's example.

mkdir sayhi-nairi && cd sayhi-nairi
npm init --yes

In my case, the command name is hello, you can choose something else.

{
// ...
"bin" : {
"hello" : "./hello.js"
}
}

At this point, all we need to do is publish our library and attempt a global installation to observe its behaviour.

npm publish

Voila!

https://www.npmjs.com/sayhi-nairi

Using which command you can see where npm stored that executable.

For additional information, refer to the NPM documentation and experiment with different features to explore what else you can achieve.

***

Thank you, feel free to ask any questions or tweet me @nairihar

Also follow my “JavaScript Universe” newsletter on Telegram: @javascript

--

--

nairihar

Sharing valuable insights on the latest tools and trends in JavaScript. nairi.dev