A simple, beginner-friendly guide to setting up a Node.js project from scratch. Learn how to initialize a project, run a development server with Nodemon, work with modules, and use popular tools like Express, Joi, and UUID.
How to Set Up a Node.js Project from Scratch: Step-by-Step Guide
If you're new to Node.js and want to quickly get started with creating your own server-side application, this guide is for you. Weβll walk through the complete process of setting up a Node.js projectβfrom initializing with npm to using Express, UUID, and Joi.
π Step 1: Initialize Your Project with NPM
The very first step is to initialize your project using:
npm initIt will ask for project details like name, version, description, entry point, etc. If you want to skip all questions and use default values, run:
npm init -yπ Step 2: Install Nodemon for Development
Nodemon automatically restarts the server when file changes are detected.
Install it as a dev dependency:
npm install nodemon -D
Create a file named index.js in your project root. This will be your server's entry file.
touch index.js
βοΈ Step 3: Configure Scripts in package.json
Edit your package.json file to add a custom script for development:
"scripts": {
"dev": "nodemon index.js"
}
Now you can start the development server using:
npm run dev
π Step 4: Create a Utility Module
You can create a utility file add.js and define a function to export:
function add(a, b) {
return a + b;
}
module.exports = add;
Then, in another file:
const add = require('./add');
console.log(add(5, 9)); // Output: 14
π Step 5: Export/Import Multiple Methods
You can also export multiple functions from a single module:
function add(a, b) { return a + b; }
function sub(a, b) { return a - b; }
function mul(a, b) { return a * b; }
module.exports = {add,sub,mul};Then in index.js:
const { add, sub, mul } = require('./add');
console.log(sub(10, 3));
π Step 6: Global Variables in Node.js
Node.js has some useful global variables:
console.log(__dirname); // Path of current directory
console.log(__filename); // Full path of current file
π§ͺ Step 7: Install and Use Express
To build an HTTP server using Express, first install it:
npm install express
Create or update your index.js:
const express = require('express');
const app = express();
const PORT = 3000;
app.listen(PORT, () => console.log(`π Server running on http://localhost:${PORT}`));
π¦ Step 8: Read POST Data with body-parser
To handle POST request data, install:
npm install body-parserThen use it in your app:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
π Step 9: Generate Unique IDs with UUID
Install UUID:
npm install uuid
Usage:
const { v4: uuidv4 } = require('uuid');
console.log(uuidv4());
π Step 10: Validate Data with Joi
Joi is a powerful schema validator:
npm install joiExample usage:
const Joi = require('joi');
const schema = Joi.object({
name: Joi.string().min(3).required(),
price: Joi.number().required()
});
// Sample object to validate
const data = { name: "Apple", price: 25 };
const { error } = schema.validate(data);
if (error) {
console.error("β Validation Error:", error.details[0].message);
} else {
console.log("β
Data is valid");
}
Final Project Example Code
Here is your full working Node.js Express app:
you need to install the required packages:
npm install express
npm install body-parser
npm install uuid
npm install joi
npm install nodemon --save-dev
π File Structure:
project-root/
β
βββ index.js
βββ add.js
βββ package.json
π add.js
function add(a, b) { return a + b; }
function sub(a, b) { return a - b; }
function mul(a, b) { return a * b; }
module.exports = { add, sub, mul };
π index.js
const express = require('express');
const bodyParser = require('body-parser');
const { v4: uuidv4 } = require('uuid');
const Joi = require('joi');
const { add, sub, mul } = require('./add');
const app = express();
const PORT = 3000;
app.use(bodyParser.json());
console.log("Addition: ", add(10, 5)); // Output: 15
console.log("Subtraction: ", sub(10, 5)); // Output: 5
console.log("Multiplication: ", mul(10, 5)); // Output: 50
// GET route
app.get('/', (req, res) => {
res.send('Welcome to your Node.js App!');
});
// POST route with validation
app.post('/product', (req, res) => {
const schema = Joi.object({
name: Joi.string().min(3).required(),
price: Joi.number().required()
});
const { error } = schema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.details[0].message });
}
const product = {
id: uuidv4(),
name: req.body.name,
price: req.body.price
};
res.status(201).json({ message: "Product added", product });
});
app.listen(PORT, () => {
console.log(`π Server running at http://localhost:${PORT}`);
});
π package.json (scripts part)
"scripts": {
"dev": "nodemon index.js"
}
π§ Youβve Learned How To:
β
Initialize a project
β
Create and use utility modules
β
Build and run a basic Express app
β
Handle POST data
β
Generate UUIDs
β
Validate input using Joi
Now you're ready to start building scalable and powerful backend applications with Node.js π! If you'd like, I can help you add MongoDB or routing next.
β
Final Thoughts
This guide covered the essential steps to start a Node.js project from scratch and work with modules, validation, and HTTP servers. With this foundation, you're ready to build powerful backend applications!