Home > Software design >  Why control is moving to a new command-line upon running node file?
Why control is moving to a new command-line upon running node file?

Time:10-30

I'm setting up a node.js server but its not running my server file. The code for the server file:

const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
app.get('/', (req, res)=>{
    res.status(200);
    res.send("Welcome to root URL of Server");
});
  
  
app.listen(PORT =>{
console.log("hello world"  PORT);
});

my json file:

{
  "name": "cp_viz",
  "version": "1.0.0",
  "description": "none",
  "main": "index.js",
  "scripts": {
    "test": "none"
  },
  "repository": {
    "type": "git",
    "url": "none"
  },
  "keywords": [
    "none"
  ],
  "author": "none",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "nodemon": "^2.0.20"
  }
}

whenever I run the command node server.js its moving to a new command line and not logging anything.

CodePudding user response:

You should write:

app.listen(PORT, () => {
  console.log("hello world"   " ", PORT);
});

Instead of :

app.listen(PORT =>{
console.log("hello world"  PORT);
});

Next install nodemon as a development dependency npm install --save-dev nodemon, and use this command in your package.json file =>

"dev": "nodemon server.js"

And run the npm run dev in your console ! And That's it !

server.js

const express = require("express");
const app = express();
const PORT = 3000;
app.use(express.json());
app.get("/", (req, res) => {
  res.status(200);
  res.send("Welcome to root URL of Server");
});

app.listen(PORT, () => {
  console.log("hello world"   " ", PORT);
});

Output Visual Studio Code

enter image description here

Output in the browser (localhost) http://127.0.0.1:3000:

enter image description here

  • Related