node shebang: executing javascript as a script

2020-11-10

 | 

~1 min read

 | 

182 words

To get a Node file to run from the command line without needing to tell the command line to use Node to interpret the file, we need a shebang.

Let’s see a Hello, world example:

hello.js
console.log('hello, world)

Without the shebang, our file, hello.js can still be run from the command line:

node hello.js
hello, world

Javascript can also be used as a scripting language, however, so that’s where the shebang comes in.

Modifying our hello.js slightly, we add a line to the top of the file to tell the interpreter how to interpret the file:

hello.js
#!/usr/bin/env node
console.log('hello, world);

Now, as long as our user permissions for the file include executing, we can run it without passing in node as the first argument:

./hello.js

This is all information I’d learned at some point in the past and forgotten. Hopefully this post will be easier to find and reference because I find scripting to be one of the most rewarding aspects of programming. Writing small scripts that automate tedious activities is like magic!


Related Posts
  • TS-Node: Running Typescript files as scripts


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!