Flying Santa
Kimkorng

How To Getting Started With Node.js

16 JAN, 2024

[read] Node.js is a free, open-source, cross-platform JavaScript runtime environment that lets developers create servers, web apps, command line tools, and scripts.

Prerequisites

  • Download and install Node.js from https://nodejs.org/.
  • npm (Node Package Manager): Included with Node.js installation.

Create a Node.js Project

  • Open terminal or command prompt.
  • Create a new project directory: mkdir my-mvc-app
  • Navigate to the directory: cd my-mvc-app
  • Initialize node project: npm init -y

Install Dependencies

  • Install Express.js (web framework): npm install express
  • Install Nodemon (for automatic restarts): npm install -g nodemon
  • Install Mongoose (MongoDB ODM): npm install mongoose
  • Install EJS (templating engine): npm install ejs

Set Up MVC Structure

  • Create Models, Views, Routes, and Controllers folders:
    shell
    mkdir models views routes controllers

Create an Entry Point (index.js)

  • Create index.js in the root directory:
    JavaScript icon
    javascript
    const express = require('express'); const app = express(); const mongoose = require('mongoose'); const path = require('path'); const usersRoutes = require('./routes/usersRoutes'); // Connect to MongoDB mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('Could not connect to MongoDB', err)); // Middleware for parsing JSON and form data app.use(express.json()); app.use(express.urlencoded({ extended: true })); // Set view engine app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); // Use routes app.use('/users', usersRoutes); // Server settings const port = process.env.PORT || 3000; app.listen(port, () => { console.log('Server listening on port ' + port); });

Create a User Model (models/accounts/user.js)

  • Create user.js in the accounts folder:
    JavaScript icon
    javascript
    const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true } }); const User = mongoose.model('User', userSchema); module.exports = User;

Create a Controller (controllers/usersController.js)

  • Create usersController.js in the controllers folder:
    JavaScript icon
    javascript
    const User = require('../models/accounts/user'); // Render form to create a new user const renderNewUserForm = (req, res) => { res.render('users/new'); }; // List all users const listUsers = async (req, res) => { const users = await User.find(); res.render('users/index', { users }); }; // Create a new user const createUser = async (req, res) => { const user = new User({ name: req.body.name, email: req.body.email }); await user.save(); res.redirect('/users'); }; module.exports = { renderNewUserForm, listUsers, createUser };

Create a Route File (routes/usersRoutes.js)

  • Create usersRoutes.js in the routes folder:
    JavaScript icon
    javascript
    const express = require('express'); const router = express.Router(); const usersController = require('../controllers/usersController'); // Routes for users router.get('/new', usersController.renderNewUserForm); router.get('/', usersController.listUsers); router.post('/', usersController.createUser); module.exports = router;

Create Views

  • Create users/index.ejs in the views/users folder:
    html
    <DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Users</title> </head> <body> <h1>List of Users</h1> <ul> <% users.forEach(user => { %> <li><%= user.name %> - <%= user.email %></li> <% }); %> </ul> <a href="/users/new">Add New User</a> </body> </html>
  • Create users/new.ejs in the views/users folder:
    html
    <DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>New User</title> </head> <body> <h1>Add a New User</h1> <form action="/users" method="POST"> <label for="name">Name:</label> <input type="text" id="name" name="name" required> <br> <label for="email">Email:</label> <input type="email" id="email" name="email" required> <br> <button type="submit">Create</button> </form> </body> </html>

Use Nodemon

  • Modify package.json file:

    json
    "scripts": { "dev": "nodemon index.js" }
  • Start the server with Nodemon: npm run dev

  • Nodemon will automatically restart the server whenever you make changes to files.

SHARE