Organizing Your Node.js REST API with Express: An Advanced Folder Structure
To create an advanced folder structure in Node.js with Express for a REST API, you can follow these steps:
Create a folder for your project and navigate to it in your terminal.
Initialize a new Node.js project by running
npm init
and follow the prompts.Install Express by running
npm install express
.Create an
index.js
file in your project folder and require Express in it:
const express = require('express');
const app = express();
- Define your routes and endpoints. For example, you can create a
users
folder with anindex.js
file inside it to handle all user-related endpoints:
// users/index.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
// get all users
});
router.post('/', (req, res) => {
// create a new user
});
router.get('/:id', (req, res) => {
// get a specific user by ID
});
router.put('/:id', (req, res) => {
// update a specific user by ID
});
router.delete('/:id', (req, res) => {
// delete a specific user by ID
});
module.exports = router;
- In your
index.js
file, require theusers
router and use it as middleware:
// index.js
const express = require('express');
const app = express();
const usersRouter = require('./users');
app.use('/users', usersRouter);
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
This creates an advanced folder structure with separate files for each endpoint, organized by resource (in this case, users). The users/index.js
file exports an Express router that can be used as middleware in the main index.js
file.
You can repeat this pattern for other resources in your API, such as products
, orders
, or reviews
.