Due to its event-driven, non-blocking I/O architecture, Node.js excels at server-side applications. It operates within a single thread, efficiently handling multiple concurrent requests without the overhead of creating a new thread for each one. Node.js leverages asynchronous I/O capabilities built into its core library, preventing JavaScript code from becoming blocked while waiting for operations like file system access or network requests to complete.
Example Server
Let’s run through some code to see Node.js as a server. It’s the sweet spot to use.
const { createServer } = require('node:http');
const hostname = '127.0.0.1';
const port = 3000;
const server = createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
This example creates a server on your localhost and port 3000. To run this go to the terminal and type node server.js(or whatever you named the file) and you should see this.
The output isn’t too exciting but is a step in the right direction.
Most Node.js applications run on the server as it shines there. However, you can use it for other things as well. Let’s understand what we did.
const { createServer } = require('node:http');
This line gets the HTTP module. This is one of the many libraries Node.js has to check the rest out here.
Then we set up the two parameters to pass in to create the server.
const hostname = '127.0.0.1';
const port = 3000;
This code creates the server and sets the status code to 200. This is for success. Remember 400s are errors(think 404 page not found!).
const server = createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
The header is set for the content type. Then we put the message.
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
This code takes the port and hostname parameters and has the server listen at that location. That is where Node.js works for us.
A quick word about JavaScript. If you’re not as familiar with it it may be helpful to brush up on it. I might suggest a short book to get you started Just the basics of JavaScript.