Running JavaScript Shell Script from Node.js
Instead of the usual web browser, this tutorial takes you on the route of using a stand-alone JavaScript shell first to execute JavaScript code. The interpreter chosen here is Node.js.
Detailed instructions on installing Node.js via the package manager can be found following the link below
https://nodejs.org/en/download/package-manager/
To quick test if the installation is correct, check the version of Node.js installed from the terminal
node -v
In Ubuntu systems, it would be
nodejs -v
It should give the version number, something like
v11.12.0.
After installing Node.js, open a text editor and create a JavaScript
file, say, hello.js. Add the following
shebang interpreter directive to the file as its first line of script
#!/usr/bin/env node
(In some operating systems, like Ubuntu, this line could be
#!/usr/bin/env nodejs.)
As in any other programming language, we start by printing "Hello,
World!" into the terminal. To achieve this, we append the line
console.log("Hello, World!"); to the file
and save it
#!/usr/bin/env node
console.log("Hello, World!");
Next, we type a command in the terminal to mark
hello.js as executable
chmod u+x hello.js
The script file can now be executed from the terminal by running the command
./hello.js
Executing Explicitly
The hello.js script file can also be
executed explicitly by specifying the Node.js interpreter. Assuming
that you are in the same location as
hello.js, type
node hello.js
in the terminal and the script will be executed. If you are in some
other location, specify the path to
hello.js after the
node command.
Notes
- The .js extension for the script file specifies that the file contains JavaScript code. But in this case, it would have run even with the .sh extension.
-
The location of the Node.js interpreter can be found with the
command
which node. The shebang interpreter directive could also have have been hardcoded to this path as#!/usr/bin/nodeinstead of#!/usr/bin/env node. -
The
chmod u+x hello.jscommand is basically to make the file executable. The "u" after "chmod" stands for "user" and "x" for "execute." This can also be achieved via the GUI in most operating systems. For example, in Ubuntu, the equivalent procedure is to right-click on the file, select thePermissionstab, and checkAllow executing file as program.