node js hello word
- Create a new directory for your Node.js project:
- Open your terminal or command prompt.
- Navigate to the desired location where you want to create your project.
Run the command
mkdir node-project
to create a new directory called "node-project".Initialize a new Node.js project:
- Run the command
cd node-project
to enter the project directory. - Run the command
npm init
to initialize a new Node.js project. Follow the prompts to provide information about your project, such as its name, version, description, entry point, etc.
Install Express.js:
- Run the command
npm install express
to install the Express.js framework. Express.js is a popular framework for building web applications with Node.js.
Create the main JavaScript file:
- Run the command
touch index.js
to create a new JavaScript file called "index.js". This file will serve as the entry point for your Node.js application.
Write the code for a simple "Hello, World!" server:
- Open the "index.js" file in a code editor.
Add the following code to create a basic Express.js server:
```javascript const express = require('express'); const app = express();
app.get('/', (req, res) => { res.send('Hello, World!'); });
app.listen(3000, () => { console.log('Server running on port 3000'); }); ```
This code imports the Express.js module, creates a new Express application, defines a route for the root URL ("/") that sends the response "Hello, World!", and starts the server on port 3000.
Start the Node.js server:
- Run the command
node index.js
to start the Node.js server. You should see the message "Server running on port 3000" in the terminal, indicating that the server is running successfully.
Test the server:
- Open a web browser and navigate to
http://localhost:3000
. - You should see the message "Hello, World!" displayed in the browser, confirming that the server is responding correctly.
That's it! You have successfully created a simple "Hello, World!" server using Node.js and Express.js.