Let's use the which command to determine if the NodeJS node CLI is in your $PATH. If not, check out my article Install NodeJS on Linux.
~]$ which node
/usr/bin/node
Before creating a Client / Server NodeJS app, let's create a simple stand alone "Hello World" app. Create a file named app.js that contains the following console.log.
console.log("Hello World");
Use the node CLI to run app.js and "Hello World" should be displayed.
~]$ node app.js
Hello World
So far, so good!
Now let's create an HTTP server. Let's create server.js with the following markup, replacing server1.example.com with the hostname of your Linux system.
const http = require("http");
const timestamp = () => `[${new Date().toUTCString()}]`
const host = 'server1.example.com';
const port = 12345;
const requestListener = function (req, res) {
res.writeHead(200);
res.end(`${timestamp()} Hello World`);
};
const server = http.createServer(requestListener);
server.on("connection", (socket) => {
console.log(`${timestamp()} successfully connected to server.js`)
})
server.listen(port, host, () => {
console.log(`${timestamp()} server listening for connections at ${host}:${port}`);
});
Let's start server.js.
~]# node server.js
[Sat, 23 Mar 2024 03:56:40 GMT] server listening for connections at server1.example.com:12345
Let's say firewalld is running on your Linux system.
~]$ sudo systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2023-07-24 02:40:19 CDT; 7 months 29 days ago
Let's update firewalld to allow connections on port 12345. I did not use the --permanent flag because I don't want this to be a permanent change to firewalld since port 12345 is just the port I'm using for testing purposes.
~]$ sudo firewall-cmd --add-port=12345/tcp
success
~]$ sudo firewall-cmd --list-port
12345/tcp
And we should now be able to pull up the HTTP server in our web browser. Wonderful!
Did you find this article helpful?
If so, consider buying me a coffee over at