Ahmet Meliksah Akdeniz
meliksahakdeniz

meliksahakdeniz

Blog Project Part 1: Setting Workspace

Blog Project Part 1: Setting Workspace

Ahmet Meliksah Akdeniz's photo
Ahmet Meliksah Akdeniz
·Feb 8, 2022·

2 min read

Hello fellow developers! I started my first Node.js project. This project is actually homework from Patika.dev platform and started files are provided by them. I code the Node.js part only. In this blog, I will only create a workspace for the project. I already downloaded Node.js on my PC by the way.

Starting ...

Create package.json file (type npm init and hit enter). The only change I made is that main file is not index.js, but app.js.

terminal.PNG

Download Express and Nodemon

Nodemon will restart the server automatically when something is changed, so we do not restart manually with Nodemon. Since it is a development dependency put -D while installing.

Type npm install -D nodemon and hit enter.

After that type npm install express Your package.json should be like this:

nodemon and express.PNG

To use Nodemon, go to package.json and add "start": "nodemon app.js(if your main file is index.js, do it for index.js)" under the "script". After that type npm start on your terminal, then hit enter. Like this:

to use nodemon.PNG

You should see this on your terminal after you type npm start and hit enter

terminal0.PNG

Time to check if everything is alright. Go to your app.js file (if you do not have one, then make one). Afterward, write this code:

const express = require("express");   // imported express framework
const app = express(); // using express function on app constant

// this is just dummy data to check if everything is working
const blog = { id: 1, title: "Blog title", description: "Blog description" };

// getting response send to send blog constant when "/" (root folder) is the url
app.get("/", (req, res) => {
  res.send(blog); 
});

// listening to port at 3000
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server started at port ${PORT}`);
});

The app.get() takes two parameters. The first one is the route, this "/" the root URL. The second one is a callback function that takes req (request) and res (response) as parameters. With the res.send() method, we send our code (in this case blog constant) to the server.

The app.listen() method listens the server. It takes two parameters, the first one is the port. The second one is a callback function(optional).

If everything works fine, we should see this on our localhost:3000:

Final.PNG

That is all for now. Take care and keep coding.

 
Share this