Whenever you write a NodeJS (.js
) file, you can go to your terminal, enter the directory and run node {{file-name}}.js
. Ever wondered how some packages written in Node don't need this to run? Jest, Babel, Yarn, etc. A lot of them have their own commands. That's because they're executables.
And turns out, it is quite straightforward to create an executable with NodeJS. You just need to follow a few steps.
Configuring package.json
βοΈ
The package.json
has a property which is specifically to create this executable task, it's bin
field. So it will end up looking something like this:
{
"name": "create-netlify-ts",
"version": "0.1.0",
"main": "index.js",
"repository": "git@github.com:atilafassina/netlify-lambda-ts.git",
"author": "Atila Fassina <atila@fassina.eu>",
"license": "MIT",
"bin": {
"create-netlify-ts": "index.js"
}
In that case, my entry file (the one which pulls all other modules and where the task will execute from, is the ./index.js
.
Instruct the terminal π€
Your terminal runs on bash
, or zsh
, or fish
, ... it doesnβt really matter. Just add a comment to the top of your file specifying it needs to run on Node.
#!/usr/bin/env node
(function () {
console.log('Executing executable')
})()
Permission to execute πββοΈ
As a security measure, files are not executable by default. It's necessary to tap into the access permissions of our entry file (index.js
in this example).
If youβre on a UNIX based system (MacOS, Linux), you can go to your terminal, navigate to the working directory of your project and run:
chmod +x index.js
Again, index.js
is our example here.
Link for local development π
As a responsible developer, you want to check if things are in place before shipping. Now is the time to tell your package manager (yarn or npm) to instead of look for your package in the global node_modules
, to look at your local directory.
You navigate to the root of your project (the directory package.json
is located) and run
yarn link
or
npm link
When you're done, you can unlink
and things will go back to normal.
Now you're free to run your command as much as you want in your system, go back, make changes, and changes will pick up instantly (as we don't have a build step involved yet).
Whatβs next? π
Talking about build steps, it would be cool to add some type safety, maybe even some transpiling to it right?
For sure that would be rad. Weβll check how to do that on my next post, as well as how to publish it properly to npm, so it can work with npx
and yarn create
.
In the meanwhile, enjoy your first node executable and let me know down in the comments if you enjoyed this post and is waiting for the sequence! π
π
If you found this post useful, please consider sharing it with your network, that would help me a lot to continue creating more content like this. π
Cover photo by Joshua Sortino on Unsplash
Top comments (0)