Node.js / 6 MIN READ
Node Express (Server)
This is a tutorial on setting up a Node Express server and working with a JSON database, along with explanations of concepts and syntax. Step 1: Setting Up
From the original Fervor library. Examples may use older package versions.
This is a tutorial on setting up a Node Express server and working with a JSON database, along with explanations of concepts and syntax.
Step 1: Setting Up Your Node Express Server
1.1 Initializing Your Project
- Command:
npm init -y - Explanation: This command initializes a new Node.js project. The
-yflag automatically accepts the default configurations.
1.2 Installing Express
- Command:
npm install express - Explanation: This command installs the Express.js framework, which simplifies the process of building a web server.
1.3 Creating Necessary Files and Directories
- Explanation: Create a structured directory for your project as follows:
express-crud-app/
├── data/
│ └── database.json
├── routes/
│ ├── users.js
│ ├── products.js
│ └── orders.js
├── server.js
└── package.json
Step 2: Setting Up JSON Database
2.1 Creating the JSON Database
- File:
data/database.json - Explanation: This JSON file serves as a simple database to store user, product, and order data. Here’s a basic structure you can use:
{
"users": [],
"products": [],
"orders": []
}
Step 3: Creating Express Route Handlers
3.1 Setting Up Route Handlers
- Explanation: We’ll create separate route handlers for users, products, and orders in the
routesdirectory. Each file will manage the CRUD operations for its respective entity.
3.2 Reading and Writing to JSON File
- Syntax:
const fs = require('fs'); function readData() { return JSON.parse(fs.readFileSync('./data/database.json', 'utf8')); } function writeData(data) { fs.writeFileSync('./data/database.json', JSON.stringify(data, null, 2)); } - Explanation: The
fsmodule helps in reading and writing to the file system. We definereadDataandwriteDatafunctions to read and write data to our JSON database file.
Step 4: Implementing CRUD Operations
4.1 Create (POST)
- Syntax:
router.post('/', (req, res) => { const data = readData(); const newItem = { ...req.body, id: data.users.length + 1 }; data.users.push(newItem); writeData(data); res.status(201).json(newItem); }); - Explanation: This route handler creates a new item. It reads data from the database, adds a new item to it, writes the updated data back to the database, and sends a response with a 201 status code (which means “Created”).
4.2 Read (GET)
- Syntax:
router.get('/', (req, res) => { const data = readData(); res.json(data.users); }); - Explanation: This route handler retrieves all items from the database and sends them as a JSON response.
4.3 Update (PUT)
- Syntax:
router.put('/:id', (req, res) => { const id = parseInt(req.params.id, 10); const data = readData(); const index = data.users.findIndex(user => user.id === id); data.users[index] = { ...data.users[index], ...req.body }; writeData(data); res.json(data.users[index]); }); - Explanation: This route handler updates an existing item by its ID. It finds the item by ID, updates its properties, writes the updated data back to the database, and sends the updated item as a response.
4.4 Delete (DELETE)
- Syntax:
router.delete('/:id', (req, res) => { const id = parseInt(req.params.id, 10); const data = readData(); data.users = data.users.filter(user => user.id !== id); writeData(data); res.status(204).end(); }); - Explanation: This route handler deletes an item by its ID. It filters out the item with the specified ID from the database, writes the updated data back to the database, and sends a response with a 204 status code (which means “No Content”).
Step 5: Setting Up the Server
5.1 Setting Up the Server
- File:
server.js - Explanation: Set up your server and import the necessary modules and route handlers. Configure middleware to parse JSON bodies and set up routes for different entities.
- Syntax:
const express = require('express'); const userRoutes = require('./routes/users'); const productRoutes = require('./routes/products'); const orderRoutes = require('./routes/orders'); const app = express(); app.use(express.json()); app.use('/users', userRoutes); app.use('/products', productRoutes); app.use('/orders', orderRoutes); const PORT = 3000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Step 6: Testing the Application
6.1 Running the Server
- Command:
node server.js - Explanation: This command starts your server. You can now test your CRUD operations using tools like Postman or curl.
Conclusion
In this tutorial, we have created a basic CRUD application using Node.js and Express.js, utilizing a JSON file as a database. You’ve learned how to set up a server, define route handlers, and perform CRUD operations.
Remember, this tutorial represents a basic setup and can be expanded with additional features like validation, error handling, and authentication as you become more comfortable with Express.js and Node.js.
Bonus code put all together
Just in case there is confusion here is the code fully assembled. Also if you just want to get it going and play with it cut and paste. Sometimes playing with code is the way to learn.
Structure
express-crud-app/
├── data/
│ └── database.json
├── routes/
│ ├── users.js
│ ├── products.js
│ └── orders.js
├── server.js
└── package.json
data/database.json
{
"users": [],
"products": [],
"orders": []
}
routes/users.js
const express = require('express');
const fs = require('fs');
const router = express.Router();
function readData() {
return JSON.parse(fs.readFileSync('./data/database.json', 'utf8'));
}
function writeData(data) {
fs.writeFileSync('./data/database.json', JSON.stringify(data, null, 2));
}
router.get('/', (req, res) => {
const data = readData();
res.json(data.users);
});
router.post('/', (req, res) => {
const data = readData();
const newItem = { ...req.body, id: data.users.length + 1 };
data.users.push(newItem);
writeData(data);
res.status(201).json(newItem);
});
router.put('/:id', (req, res) => {
const id = parseInt(req.params.id, 10);
const data = readData();
const index = data.users.findIndex(user => user.id === id);
data.users[index] = { ...data.users[index], ...req.body };
writeData(data);
res.json(data.users[index]);
});
router.delete('/:id', (req, res) => {
const id = parseInt(req.params.id, 10);
const data = readData();
data.users = data.users.filter(user => user.id !== id);
writeData(data);
res.status(204).end();
});
module.exports = router;
routes/products.js
For the products.js and orders.js files, you can duplicate the structure of the users.js file, but replace users with products and orders respectively.
routes/orders.js
Same as the products.js, duplicate the structure of users.js, but replace users with orders.
server.js
const express = require('express');
const userRoutes = require('./routes/users');
const productRoutes = require('./routes/products');
const orderRoutes = require('./routes/orders');
const app = express();
app.use(express.json());
app.use('/users', userRoutes);
app.use('/products', productRoutes);
app.use('/orders', orderRoutes);
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Now, to initialize your project and install express, run the following commands in the project root directory (express-crud-app/):
npm init -y- to initialize your project.npm install express- to install the Express.js library.
After running these commands, you can run your server using the command node server.js.
This setup forms a basic CRUD application with separate routes and handlers for users, products, and orders, all interacting with a simple JSON file as the database. Please adapt and expand upon this basic structure as per your needs.