The most common example ‘Hello World’ of Node.js is a web server:

const http = require('http')
const hostname = '' const port = 3000
const server = http.createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello World\n') })
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
}) code-box

            To run this snippet, save it as a server.js file and run node server.js in your terminal. The code first includes the Node.js http module. Node.js has an amazing standard library, including a first-class support for networking. The createServer() method of http creates a new HTTP server and returns it.

            The server is set to listen on the specified port and hostname. When the server is ready, the callback function is called, in this case informing us that the server is running. Whenever a new request is received, the request event is called, providing two objects: a request (an https.IncomingMessage object) and a response (an http.ServerResponse object).

            Those 2 object are essential to handle the HTTP call. The first provides the request details. In this simple example, this not used, but you could access the request headers and request data. The second is used to return data to the caller.

In this case with

            res.statusCode = 200 code-box

We set the statusCode property to 200, to indicate a successful response.

We set the Content-Type header:

            res.setHeader(‘Content-Type’,’text/plain’) code-box

and we end close the response, adding the content as an argument to end():

            res.end(‘Hello World\n’) code-box


Previous Post Next Post

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel