First Node.js Application
To create a basic Hello World first application in Node.js, save the following single line JavaScript as hello.js file.
console.log(“Hello James Bond!”);
Open a PowerShell (or command prompt) terminal in the folder in which hello.js file is present, and enter the following command. The “Hello James Bond!” message is displayed in the terminal.
PS D:\nodejs> node hello.js
Hello World
To create a “Hello, World!” web application using Node.js, save the following code as hello.js:
http = require('node:http');
listener = function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/html
response.writeHead(200, {'Content-Type': 'text/html'});
// Send the response body as "Hello World"
response.end('<h2 style="text-align: center;">Hello James Bond!</h2>');
};
server = http.createServer(listener);
server.listen(3000);
// Console will print the message
console.log('Server running at http://127.0.0.1:3000/');
Run the above script from command line.
C:\nodejs> node hello.js
Server running at http://127.0.0.1:3000/
The program starts the Node.js server on the localhost, and goes in the listen mode at port 3000. Now open a browser, and enter http://127.0.0.1:3000/ as the URL. The browser displays the Hello World message as desired.
Follow below images.
Recent Comments