My Logo

PUBLISHED APRIL 19, 2024

Teghen Donald Ticha
Lastly Updated: 3 months ago
Reading time 13 mins

Running NodeJS Scripts

Master the command line interface for executing nodeJS scripts efficiently. Learn common options and best practices for seamless script execution
Running NodeJS Scripts

Prerequisite

Basic familiarity with the command line interface (CLI) in any other language, platform or even just terminal environment is recommended, although not required.

No prior experience with nodeJSis required, but a general understanding of its purpose and usage would be beneficial.

If you're new to node and need some background with environment set up, then, check out this quick guide on .

In the world of NodeJS development, mastering the command line interface (CLI) is essential for efficiently executing JavaScript code outside of a browser environment.

Whether you're a beginner exploring the basics or an experienced developer seeking to optimize your workflow, understanding the various methods and common command line options for running Node.js scripts is key.

In this seriess part, we'll discuss some fundamentals of running NodeJS scripts from the CLI.

We'll explore different approaches, from using the `node` command to executing scripts with `shebang` notation and leveraging tools like `npx` and `pkg`.

Along the way, we'll uncover common command line options and best practices for seamless script execution.

First let's start with setting up nodeJS and get our environment ready to go.

Setting Up Node.js

Before we can start running Node.js scripts from the command line, we need to ensure that Node.js is properly installed on our system.

Fortunately, setting up Node.js is a straightforward process, regardless of your operating system.

Installing Node.js:
  1. 1.Download NodeJS: Visit the official NodeJS website and download the appropriate installer for your operating system.
  2. 2.Install NodeJS: Follow the installation instructions provided by the installer. NodeJS typically includes both the Node runtime and the npm package manager.
  3. 3.Verify Installation: After installation, open your terminal or command prompt and run the following commands to verify that NodeJS and npm are installed correctly:
node -v
npm -v

These commands should print the installed versions of Node.js and npm, respectively.

Now the above is pretty straightforward, but in some cases, you may encounter some issues. If that happens, then check out this guide for a more detailed overview of the setup process : .

The most common and straightforward way to execute nodeJS scripts is by using the node command in the command line interface.

With the node command, you can run :

  • JavaScript files directly,
  • execute inline code, and
  • pass command line arguments to your scripts.
Executing JavaScript Files:

To run a nodeJS script saved in a file, simply navigate to the directory containing the script in your terminal and use the node command followed by the filename:

node script.js

Assuming your file is also named `script.js`, this command will execute the script and output the result(if any) to the console.

Executing Inline Code:

In addition to running script files, you can also execute JavaScript code directly from the command line using the `-e` flag followed by the code to execute:

node -e "console.log('C\'est moi, NodeJS😎')"

This command should print `C'est moi, NodeJS😎` to the console.

Common Command Line Options:

The node command supports several command line options to customize script execution. Let's go through a few common ones.

  • -e <script>: Execute JavaScript code passed as a string argument as shown above
  • -r <module>: Preload a `module` before executing the script.
node -r esm script.js

In the place of esm, you used cjs which is the default module system for node.

NB: NodeJS doesn't support ESM out of the box when you run files with the .js extension. To enable ESM support, you need to use the -r flag to load the ESM module.
Also, you will need to install esm in you computer, else you will get an error.


Using ESM module system, let's you use modern javascript syntax like `import` instead of require when loading modules.

node -r esm -e "import fs from 'fs'; fs.access(filePath, (err) => { if (!err) console.log('You have access!'); })"

Make sure you've install esm npm install -g esm before running the above command.

  • --watch: Automatically restart script on file changes.
node --watch script.js

This command watches the specified script file for changes and automatically restarts the script whenever modifications are detected, facilitating development workflows.

Test:
- Add this line to the script.js file console.log("Initial content") and run the above command in your terminal.

- Change the content to console.log("Updated content").


As you can see, by leveraging these options, you can tailor the behavior of the node command to suit your specific requirements and workflows.

Above, you are explicitly telling the shell to run your script with node. But there are other ways to execute nodejs script and we'll explore a few below.

Using Shebang

In Unix-like operating systems (such as Linux and macOS), the shebang (#!) notation is used to specify the interpreter for executable scripts. By including a shebang line at the beginning of a script file, you can indicate the path to the interpreter that should be used to execute the script.

The shebang line consists of the characters `#!` followed by the path to the interpreter.

For Node.js scripts, the shebang line typically points to the `node` interpreter.

#!/usr/bin/env node

This shebang line tells the system to use the node interpreter located in the system's environment (/usr/bin/env) to execute the script.

NB: You can find you current node executable path by running the following command in your terminal: which node

Creating Executable Scripts:

To create an executable Node.js script with shebang, follow these steps:

  • Add Shebang Line: Open your text editor and add the shebang line at the beginning of your NodeJS script file.
#!/usr/bin/env node

console.log('Hello, world!');

NB: Make sure you replace the execution path (/usr/bin/env) with yours!


  • Make Script Executable: Make the script file executable using the chmod command:

    The `chmod` command stands for `change mode` and is used to modify the file mode bits of a file. In the context of making scripts executable, we use `chmod` to add the execute permission to the script file.
chmod +x script.js


  • Execute Script: Now you can run the script directly from the command line without specifying the node interpreter:
./script.js

You should get hello, world log on the terminal output.


Benefits of Shebang:

Using shebang to execute nodeJS scripts offers several benefits:

  • Portability: Shebang allows scripts to be executed across different Unix-like systems without hardcoding the path to the interpreter.
  • Ease of Use: Once a script is made executable, it can be run like any other command, simplifying execution.
  • Flexibility: Shebang provides flexibility in specifying the interpreter, enabling the use of different nodeJS versions or alternative interpreters.

When running nodeJS scripts from the command line, there are several common options and best practices to consider.

These options can enhance the execution process and provide additional functionality to your scripts.

Some Command Line Options

  • --inspect: Enables the Node.js inspector for debugging and profiling. It allows you to connect Chrome DevTools or any other inspector client to debug and profile your nodeJS applications.
node --inspect script.js


  • --require: Preloads a module before executing the script. This option is useful for loading modules such as `dotenv` for environment configuration or custom utilities.
node --require dotenv/config script.js


  • --experimental-modules: Enables support for ECMAScript modules (ESM), which allows you to use import and export statements instead of require().
node --experimental-modules script.mjs


For the full list of options available for use, visit the offical page or use this command to list out all option: node -help.


Conclusion

Running nodeJS scripts from the command line is a fundamental aspect of Node.js development, enabling developers to execute scripts, automate tasks, and build powerful applications.

By leveraging command line options, best practices, and troubleshooting strategies, developers can optimize script execution, enhance reliability, and streamline development workflows.

Moving Forward: As you continue to develop nodeJS applications and scripts, remember the importance of running scripts effectively from the command line.

It's important to stay informed about new command line options, best practices, and tools that can improve your development experience and streamline your workflow.

By upping your skills in running nodeJS scripts from the command line, you can unlock the full potential of node and build robust, efficient applications that meet the needs of your users and stakeholders.

In the next part, we'll discuss reading and setting environment variable in nodeJS.


All Chapter Parts for NodeJs In Theory, An absolute Beginner’s Overview
  1. Chapter 1 , Part 1 : Introduction to NodeJS

    In this series part, I introduce nodeJS and some technical concepts associated with it. I also show how easy it is to setup and start a simple nodeJS web server.

  2. Chapter 1 , Part 2 : How to Install and Setup NodeJS

    In this series part, I run you through the various ways to install nodeJS. I also discuss how to install nvm and use it to switch between different node versions.

  3. Chapter 1 , Part 3 : How much JavaScript do you need to learn NodeJS

    In this series part, we explore the nuanced relationship between JavaScript and NodeJS, highlighting some subtle distinctions between the two environments.

  4. Chapter 1 , Part 4 : The v8 Engine and the difference Between NodeJS and the browser

    In this series part, we explore the V8 engine and how it interacts with nodeJS. We also discuss node’s event loop and uncover the mystery behinds node’s ability to handle concurrent operations.

  5. Chapter 1 , Part 5 : NPM, the NodeJS package manager

    Discover the essentials of npm, the powerful package manager for Node.js. Learn installation, management, publishing, and best practices

  6. Chapter 1 , Part 6 : NodeJS in Development Vs Production

    Explore how Node.js behaves differently in development and production environments. Learn key considerations for deploying Node.js applications effectively.

  7. Chapter 2 , Part 1 : Asynchronous Flow Control

    In this series part, we'll explore various aspects of asynchronous flow control in Node.js, from basic concepts to advanced techniques.

  8. Chapter 2 , Part 2 : Blocking vs Non-blocking I/O

    Explore the differences between blocking and non-blocking I/O in Node.js, and learn how to optimize performance and scalability.

  9. Chapter 2 , Part 3 : Understanding NodeJS Event loop

    Exploring the Node.js event loop by understanding its phases, kernel integration, and processes enabling seamless handling of asynchronous operations in your applications.

  10. Chapter 2 , Part 4 : The NodeJS EventEmitter

    Explore the power of Node.js EventEmitter: an essential tool for building scalable and event-driven applications. Learn how to utilize it effectively!

  11. Chapter 3 , Part 1 : Working with files in NodeJS

    Gain comprehensive insights into file management in Node.js, covering file stats, paths, and descriptors, to streamline and enhance file operations in your applications.

  12. Chapter 3 , Part 2 : Reading and Writing Files in NodeJS

    Uncover the fundamentals of reading and writing files in nodeJS with comprehensive examples and use cases for some widely used methods.

  13. Chapter 3 , Part 3 : Working with Folders in NodeJS

    Unlock the secrets of folder manipulation in Node.js! Explore essential techniques and methods for working with directories efficiently

  14. Chapter 4 , Part 1 : Running NodeJS Scripts

    Master the command line interface for executing nodeJS scripts efficiently. Learn common options and best practices for seamless script execution

  15. Chapter 4 , Part 2 : Reading Environment Variables in NodeJS

    Learn how to efficiently manage environment variables in nodeJS applications. Explore various methods and best practices for security and portability

  16. Chapter 4 , Part 3 : Writing Outputs to the Command Line in NodeJS

    Learn essential techniques for writing outputs in nodeJS CLI. From basic logging to formatting and understanding stdout/stderr.

  17. Chapter 4 , Part 4 : Reading Inputs from the Command Line in NodeJS

    Learn the various ways and strategies to efficiently read command line inputs in nodeJS, making your program more interactive and flexible.

  18. Chapter 4 , Part 5 : The NodeJS Read, Evaluate, Print, and Loop (REPL)

    Explore the power of nodeJS's Read, Evaluate, Print, and Loop (REPL). Learn how to use this interactive environment for rapid prototyping, debugging, and experimentation.

  19. Chapter 5 , Part 1 : Introduction to Testing in NodeJS

    Discover the fundamentals of testing in nodeJS! Learn about testing types, frameworks, and best practices for building reliable applications.

  20. Chapter 5 , Part 2 : Debugging Tools and Techniques in NodeJS

    Explore essential debugging tools and techniques in Node.js development. From built-in options to advanced strategies, and best practices for effective debugging.

  21. Chapter 6 , Part 1 : Project Planning and Setup

    Discuss the planning and design process for building our interactive file explorer in Node.js, focusing on core features, UI/UX design, and implementation approach and initial setup.

  22. Chapter 6 , Part 2 : Implementing Basic functionalities

    In this guide, we'll implement the basic functionalities of our app which will cover initial welcome and action prompts.

  23. Chapter 6 , Part 3 : Implementating Core Features and Conclusion

    In this guide, we'll complete the rest of the more advanced functionalities of our app including, create, search, sort, delete, rename and navigate file directories.