DEV Community

Cover image for How to create and setup a Node.js server port 🌐
Arslan
Arslan

Posted on

How to create and setup a Node.js server port 🌐

What is Node.js?

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment designed to execute JavaScript code outside a web browser. It allows developers to build scalable network applications using JavaScript.

Install Node and npm

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

Get package.json file

Create a folder for your app, add a server.js file inside, and navigate to that folder. Run npm init in the terminal, providing information like version and description. Make sure to set server.js as the entry point.

npm init
Enter fullscreen mode Exit fullscreen mode

**

Install dependencies

**

Install Express (a Node.js framework for building RESTful APIs), Mongoose (a library for connecting MongoDB and Node.js), and Nodemon (a tool for restarting the server on file changes)

npm install express mongoose
npm install -D nodemon
Enter fullscreen mode Exit fullscreen mode

Write a script

Add the following scripts to 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 = 8000;
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 the terminal

npm run server
Enter fullscreen mode Exit fullscreen mode

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

Image description

This setup lets you quickly create a Node.js server using Express, connect to MongoDB using Mongoose, and automatically restart the server during Nodemon development.

β€œKeep coding, keep sharing, stay motivated. The source code of success lies in persistence, passion, and a dash of creativity. Happy coding journey!”

Thank you for reading! 😍
Feel free to connect on Linkedin ✨

Top comments (0)