How to Create a New Node.js Application from the Terminal

Are you excited to get started with Node.js but not sure where to begin? Whether you’re a beginner or an experienced developer in need of a refresh, this guide will walk you through setting up a new Node.js application from scratch—all from the terminal. Let’s dive in!

1. Open Your Terminal

Open your terminal and navigate to the folder where you want to create your Node.js project. On Windows, you can use Command Prompt, PowerShell, or Git Bash. On macOS and Linux, the terminal is ready right from your command line.

2.Create a Directory for Your Project (Optional)

While this step is optional, organizing each application in its own directory is often helpful.

To create a new folder, run:

mkdir my-app
cd my-app

Replace my-app with any name you’d like for your project. This command creates a new directory and navigates into it, so your project files stay organized and separate.

3. Initialize Your Node Application

To set up your Node.js application, use the following command:

npm init

This command initializes a new package.json file, which tracks your project’s dependencies, configuration, and metadata.

During setup, npm will ask you a series of questions:

  • Package name
  • Version
  • Description
  • Entry point (usually index.js)
  • Author, License, etc.

You can press Enter to accept the default values or fill in each field according to your preference. If you want to skip the prompts and use defaults, run:

npm init -y

This command instantly generates a package.json file with default settings.

4.Install Dependencies (Optional)

If your project requires any dependencies, install them with:

npm install <package-name>

For example, if you want to use Express for web development, install it by running:

npm install express

This command automatically updates your package.json and package-lock.json files with the dependency details.

5. Create an Entry File

The entry file, typically index.js, serves as the starting point for your application. To create it, use the following command:

touch index.js

Alternatively, you can create it through your code editor or any other method. This file will hold the code that runs when you start your Node.js application.

6. Add a Simple Script

Let’s write a basic “Hello, World!” script. Open index.js in your preferred text editor and add:

console.log("Hello, World!");

This line of code will output “Hello, World!” to the terminal when you run the file.

7. Run Your Application

Now that everything is set up, you’re ready to run your first Node.js application! In the terminal, enter:

node index.js

You should see Hello, World! printed in your terminal, confirming that your setup works correctly.

Wrapping Up

Remember, Node.js is incredibly flexible and powerful. This basic setup can be expanded into a full-stack application with the right tools and libraries, such as Express, MongoDB, and more. Happy coding!