Creating a simple "Hello, World!" application in Node.js is straightforward.
Follow these steps to set up a basic Node.js server:
Install Node.js: Ensure that Node.js is installed on your system. You can download it from the official website: Node.js Downloads
Create a Project Directory: Create a new directory for your Node.js project. Open a terminal or command prompt and navigate to the directory where you want to create the project.
Initialize the Project: Run the following command to initialize a new Node.js project and create a package.json
file:
npm init -y
Create the Server File: Create a file named app.js
(or any other preferred name) in your project directory. Open the file in a text editor and add the following code:
// app.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Run the Server: In the terminal, run the following command to start your Node.js server:
node app.js
This will start the server, and you should see the message "Server running at http://127.0.0.1:3000/" in the console.
Access the Hello World Page: Open your web browser and navigate to http://127.0.0.1:3000/. You should see the "Hello, World!" message displayed.
Congratulations! You've just created a simple Node.js "Hello, World!" application. This is a basic example to get you started, and from here, you can explore and build more complex applications using the features and modules available in the Node.js ecosystem.