Backend/Node.js

Creating a Server with Node.js

Jin-Co 2023. 8. 17. 20:24
반응형

The web server contains all the information about the application and allows users to access the data. Typically, getting the request and sending the data is done with HTTP(S), and today we will see the ways to create a server using the native Node.js module, 'http', in Node.js

List of Contents

Installing Node.js

 

NPM

npm is a JavaScript library that provides various codes ready to be used. It is the world's biggest open-source library that anyone can use and anyone can create and share their code without having to pay (But the private package is not free). We need to i

jin-co.tistory.com

Creating a Project

Run the command below to initialize the npm package

npm init

We can add a '-y' option as shown below to mark everything as 'yes' when creating a new project (This can be changed in the package.json later).

npm init -y

Create a .js file to create a server (Conventionally, server.js or app.js are mostly used).

Creating a Server

Import the 'http' in the file we just created

const http = require('http')

Assign a port number

const http = require('http')

const server = http.createServer(function(req, res) {
  if(req.url === '/') {
    res.end('server')
  }
})

server.listen(3000)

Run the Node.js with the command shown below

node index.js

You will see the server running on the specified port of your choice.

Run

There are many ways to run the created server from running directly to using third-party libraries.

Using Node.js Command

Run the command shown below in the command line

node index.js

Then you will see the server running

Using Nodemon

 

NPM - Nodemon

Usually, to reflect the changes in the backend on the front end when developing an app, we have to save changes and rerun the server. Nodemon is a live server library that reflects the changes automatically without us having to do so. Implementation Instal

jin-co.tistory.com

In this writing, we have seen how to create a Node.js server with http module and I hope this was helpful.


References

Node.js HTTP Module (w3schools.com)

 

Node.js HTTP Module

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

HTTP | Node.js v19.6.1 Documentation (nodejs.org)

 

HTTP | Node.js v19.6.1 Documentation

HTTP# Source Code: lib/http.js To use the HTTP server and client one must require('node:http'). The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possi

nodejs.org

728x90
반응형