Setting up the Start Scripts and Running the Server
Learn how to start up the server for any project.
We'll cover the following
Previously, we set up our backend’s structure and architecture and installed all the necessary npm
packages. To start our Node.js application in this lesson, we need to require the Express framework in our server.js
file. However, before we do that, let us set up the server port.
Setting up the port
Inside our .env
file, we configured our server to run on port 5000
, which means we’ll create a variable in our server.js
file to have access to this port. Following is how we do this:
const PORT = process.env.PORT || 5000
when hosted on a cloud service provider. The web server will first try to access the environment variable on process.env.PORT
. If there’s nothing there, it will use the second option with the number 5000
. The PORT
variable above helps inform the web server what port to listen to
Starting up the server
The next step to starting up the server requires the Express framework inside our server.js
file.
const express = require('express')
const app = express()
Above, after requiring the Express framework, we call the express()
function and pass it inside the app
variable. The next step we take to start up the application is to listen to the port where we’re serving the application.
app.listen(PORT, () => {
console.log(`Server Running on Port ${PORT}`)
})
Above, we do the following:
-
Use the
app.listen()
function to bind and listen to the connection on the specified port. -
Inside the
app.listen()
function, we log the port of our server by using the console.log method to ensure that our application runs perfectly.
The final step we need to implement is to configure our start-script
object in our package.json
file:
"scripts": {
"start": "nodemon server.js"
},
From the above code, we can take note of the following:
-
The first part of the start key has a value called
nodemon
, which helps us automatically restart our server. -
The second part contains the name of the file we want to serve, called the
server.js
file.
After taking the following steps above, our back-end application should have the following code below:
Get hands-on with 1400+ tech skills courses.