Creating the Server!

STEP 1: Open PowerShell and find the base project directory

Run the command "code ." omitting the quotes, to open Microsoft Visual Studio.

STEP 2: Create "app.js", ".env", ".gitignore" in base folder

You're also going to want to open the package.json and find the section labeled "scripts"

In the brackets, paste this line of code

  • "start": "nodemon app.js"
  • STEP 3: Start Writing the Server Code

    This is where the magic begins to happen. Here is the basic code to get this server functioning. All you need to do is copy it into the app.js file that we created.

    //will work with the .env file to hold the database's url and other enviornment variables
    require('dotenv').config();
    
    //calls and setts the express framework
    const express = require('express');
    const app = express();
    
    //this will act as the arm that accesses the MongoDB database
    const mongoose = require('mongoose');
    
    //This line is listening to port 3000 and will log when we run app.js
    app.listen(3000, () => console.log('Server Started'));
    

    With just those five lines of code, we have successfully created a server using Express framework and Node.js

    Now to run it, run this line in either VS code's Java console or the PowerShell:

    npm run start
    

    This line refers to the script that we defined earlier in the package.json file.

    If everything was done correctly, you should receive that bottom line that says "Server Started". A great feature of nodemon is that whenever the project is saved, the server gets restarted. I have noticed that it only tends to restart when files in the base Dir folder are saved.