In this tutorial you will learn how to create simple Node Js server with no packages at all just pure Node Js core modules.
programs and versions:
nodejs: v18.19.0
npm: v10.2.3
vscode: v1.85.2
should work on any nodejs > 14
Now lets start:
I assume that you had node js installed on your device if not go to nodejs and download and install LTS version (20.11.0 On the date of writing this article)
create server.js:
first we need to create new file named server.js then copy this code:
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello World!');
});
const PORT = 2121;
server.listen(PORT, 'localhost', () => {
console.log(`server run on port ${PORT}`);
});
first line we required "http" core module to create our node js server by use it in this code:
http.createServer((req, res) => {
res.end('Hello World!');
});
- "http.createServer" to create the server
- the callback function (req, res) => { ... } is called every time a request is made to the server.
- The "req" parameter represents the request object, and "res" represents the response object.
- "res.end" Ends the response by sending the specified string as the response body. In this case, it sends the string "Hello World!".
and to run the server we call "server.listen" with port 2121
now to run and test the server just write this code in terminal:
node server.js
if everything is right you should see in terminal;
server run on port 2121
and to test the server open the browser and go to localhost:2121 and you will see "Hello World!" in the browser.
simple right :)
Conclusion:
it's very easy and simple to create server with node js without any package but if you want to build big more complex application it will be better to use very common used packages like Express.js or Koa.js (this packages i use)
But I will continue to write a few articles on how to build nodejs server in the next articles i will show you how to serve an html and Json data as response.
Top comments (0)