Node Js “Hello World” web app is a simple web application that displays a message, usually “Hello World!”, in a web browser. It’s often used as a starting point for learning how to build web applications, as it provides a simple example of how to serve content over the web.
Before start you first read this tutorial: NodeJs Hello World
Node.js is commonly used to build server-side APIs, real-time web applications, and microservices.
First you have to install install Node.js:
- Go to the Node.js website (https://nodejs.org) and click the “Download” button for the LTS version.
- Choose the appropriate installer for your operating system (Windows, macOS, or Linux).
- Once the download is complete, run the installer and follow the prompts to complete the installation.
- After the installation is complete, open your terminal and type
node -v
to check that Node.js was installed correctly. This command should output the version of Node.js that was installed.
Node JS Hello World Web App example
Simple example code to build a web server in Node.js. Once we have installed Node.js, let’s build our first web server.
- Create a new file named
app.js
in your preferred code editor. - Copy and paste the following code into
app.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer(function(req, res) {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, function() {
console.log('Server running at http://'+ hostname + ':' + port + '/');
});
3. Open your terminal and navigate to the directory where app.js
is saved.
4. Run the command node app.js
to start the web server.
5. Open your web browser and navigate to http://localhost:3000
.
Output:
You can now modify the response as needed to serve HTML, JSON, or other types of content, and you can add more routes and functionality to build a complete web application.
To stop the server that you started using Node.js, you can simply use the keyboard shortcut Ctrl + C
in the terminal where the server is running.
Alternatively, if you want to stop the server programmatically from within the code, you can call the close()
method on the server object. Here’s an example:
const server = http.createServer(function(req, res) {
// ...
});
// Start the server
server.listen(port, hostname, function() {
console.log('Server running at http://'+ hostname + ':' + port + '/');
});
// Stop the server after 10 seconds
setTimeout(function() {
server.close();
console.log('Server has been stopped');
}, 10000);
Do comment if you have any doubts or suggestions on this NodeJs basic topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version