Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Creating and Running a Node.js Application

Creating and Running a Node.js Application

Creating and running a Node.js application involves several steps, from setting up the project structure to writing code and executing it. Here's a step-by-step guide to help you create and run a simple Node.js application:

Step 1: Set Up a Project Directory

1. Create a new directory for your project. Open a terminal or command prompt and navigate to the location where you want to create the project.
 
mkdir my-node-app
cd my-node-app
 

Step 2: Initialize the Project with npm

2. Use the following command to initialize your project. This will create a package.json file, which is a configuration file for your Node.js application.
npm init -y
npm init -y
 

Step 3: Create Your Main JavaScript File

3. Create a JavaScript file (e.g., app.js) using a text editor. This will be the entry point of your Node.js application.
 
// app.js

function greet() {
  console.log('Hello, World!');
}

greet();
 

Step 4: Running the Application Locally

4. In your terminal, run the Node.js application using the following command:
node app.js
 
You should see the output:
Hello, World!
 
Congratulations! You've successfully created and run a simple Node.js application.
 

Step 5: Adding External Dependencies (Optional)

5. If you want to add external packages or libraries to your project, you can use npm. For example, let's say you want to use the lodash library:
npm install lodash

Copy to Clipboard
 
  
Then, you can use it in your app.js:
const _ = require('lodash');

function greet() {
  console.log(_.upperCase('Hello, World!'));
}

greet();
 

Step 6: Running a Node.js Server (Optional)

6. If you want to create a simple HTTP server, you can do so in Node.js. Create a new JavaScript file (e.g., server.js) and add the following code:
// server.js
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, World!\n');
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
 
Then, run the server using:
node server.js
 
You can access the server at http://localhost:3000.