Writing a Simple Node.js Script

Simple Node.js

Let's write a simple Node.js script that outputs "Hello, World!" to the console. To do this, we'll use the built-in "console" module.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.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}/`);
});

In this script, we first import the http module, which is built into Node.js. Then, we create a constant for the hostname and port number that our server will listen on.

Next, we use the createServer method of the http module to create an HTTP server that outputs "Hello, World!" when a request is made to the server.

Finally, we start the server using the listen method and specify the hostname and port number that the server should listen on.

Last updated