๊ฐœ๋ฐœ Code/์›น๊ฐœ๋ฐœ WebDev

[WebDev][Node.js] Setting Up a Node.js Environment and Building a Server with Express.js

5hr1rnp 2025. 2. 12. 00:15
๋ฐ˜์‘ํ˜•

1. Setting Up Node.js in VSCode


1.1. Installing Node.js

Download and install the LTS version of Node.js from the official Node.js website.
After installation, open a terminal and verify that Node.js and npm are installed correctly:

node -v  # Check Node.js version
npm -v   # Check npm version

 

 

* For Linux users, you can install Node.js and npm using the following command:

sudo apt-get install nodejs npm -y

1.2. Setting Up Visual Studio Code

 

  • Install Visual Studio Code (VSCode) if you haven't already.
  • Enhance your development experience by installing useful extensions like:
    • Babel JavaScript
    • Auto Close Tag
    • Auto Rename Tag
    • Better Comments
    • Code Runner

(You can search for and install extensions based on your preference.)


728x90
๋ฐ˜์‘ํ˜•

2. Creating a Server with Express.js


2.1. Initializing a New Project

  • Create a new project folder and open it in VSCode:
mkdir my-express-app
cd my-express-app
  • Initialize a new Node.js project using npm:
npm init -y

 

 * This creates a package.json file, which manages project dependencies.

2.2. Installing Express.js and Setting Up a Basic Server

  • Install Express.js:
npm install express
  • Create a new file called server.js and add the following code:
const express = require('express');
const app = express();
const PORT = 3000;

app.get('/', (req, res) => {
    res.send('Hello, Node.js with Express!');
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
  • Start the server:
node server.js
  • Open your browser and go to http://localhost:3000. You should see the message: "Hello, Node.js with Express!"

 

Screen after accessing localhost following the execution of server.js.

 


3. Using Nodemon for Automatic Server Restart


During development, manually restarting the server after every change can be tedious. Nodemon automatically restarts the server whenever you modify the code.

3.1. Installing Nodemon as a Dev Dependency

npm install --save-dev nodemon

 

3.2. Updating package.json Scripts

Modify the scripts section in package.json:

"scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js"
}

 

3.3 Running the Server in Development Mode

Start the server using Nodemon:

npm run dev
 
Now, whenever you make changes to your code, the server will restart automatically!
๋ฐ˜์‘ํ˜•