DEV Community

Cover image for How to setup a Node.js server port
Aneeqa Khan
Aneeqa Khan

Posted on • Updated on

How to setup a Node.js server port

What is Node.js?

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on a JavaScript Engine and executes JavaScript code outside a web browser, which was designed to build scalable network applications.

Today I want to show you a setup of the node server port so let's get into the implementation.

For this series, I'm following an excellent video tutorial from Traversy Media

Install Node and npm

First, you have to download Node and npm from these links.

Get package.json file

Create a folder with your app name and create a file with server.js in that folder.
Now navigate into that folder and type the below command in the terminal.

npm init
Enter fullscreen mode Exit fullscreen mode

It will ask you to provide the version, description, etc to type for your project. Just make sure to add server.js file for the entry point.

Install dependencies

Next, you have to install express which is the Node.js framework to create RESTful APIs and mongoose which is a JS library to create a connection between MongoDB and Node.js app.

npm i express mongoose
Enter fullscreen mode Exit fullscreen mode

and install nodemon from this command

npm i -D nodemon
Enter fullscreen mode Exit fullscreen mode

Nodemon is a tool to observe the changes in the file and restarts the server.

Write a script

Write these two scripts in your package.json file.

 "scripts": {
    "start": "node server.js",
    "server": "nodemon server.js"
  },
Enter fullscreen mode Exit fullscreen mode

Create a port

Now in the end, type this code in your server.js file

const express = require('express');
const port = 5000;

const app = express();

app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

and to get the results, run this command in terminal

npm run server
Enter fullscreen mode Exit fullscreen mode

You'll get the running port in the terminal just like this

node-server

Thank you for reading!
Feel free to connect on Twitter

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.