Node (or more formally Node.js) is an open-source, cross-platform runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for use outside of a browser context (i.e. running directly on a computer or server OS). As such, the environment omits browser-specific JavaScript APIs and adds support for more traditional OS APIs including HTTP and file system libraries.
Node is use to create simple web server using node HTTP package.
We are going to create a web server that listens to any kind of HTTP request on URL http://127.0.0.1:8000/ When the request is received, the script will respond with the string "Hello, Your Web Server Created".
Please make sure, you have node installed, If you are yet to install node, Kindly visit NODE and follow the installation instruction according to your OS.
Now let code.
Step 1 Create a folder anywhere where in your system give it an name of your choice. For me I will be calling it server. now inside server folder , create javascript file called server.js
Open the newly created file with any text editor of your choice and paste the below code.
//load http module
const http = require('http');
//create host name
const hostname = "127.0.0.1";
//createport number
const port = 8080;
//create http server
const server = http.createServer((req, res) => {
//set response http header with status and content type
res.writeHead(200, { 'Content-type': 'text/plain' });
res.end('Hello, Your Web Server Created');
});
// Prints a log once the server starts listening
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}`);
});
Now save the file in the folder you created above. and open the file with your OS terminal and type the following command
node serve.js
Finally, navigate to localhost:8080 in your web browser; you should see the text "Hello, Your Web Server Created" in the upper left of an otherwise empty web page.
Thank you for reading, I have started my node js journey today after over a year of written php with laravel framework and yet still feels like it is not enough. Stay with me and follow me to get notified for subsequent sections.