Getting Started
The library creates a simple and intuitive method of routing your application's URLs based on your file and folder structure.
Introduction
This tutorial uses JavaScript and CommonJS module types to keep things simple and quick to get started. Ready-to-run examples with TypeScript, ECMAScript module types, and more can be found in the "examples" folder.
Install
💿 Add node-file-router
to your dependency list.
- npm
- Yarn
- pnpm
npm install node-file-router
yarn add node-file-router
pnpm add node-file-router
What you'll need
- Node.js version 14 or above
Initialization
Create an server.js
file and do the following:
// 1. Import default http module and node-file-router
const http = require('node:http');
const { initFileRouter } = require('node-file-router');
// 2. Create an entry-point function
async function run() {
// 3. Initialize node-file-router and the handler function
const useFileRouter = await initFileRouter();
const server = http.createServer((req, res) => {
// 4. Create a server and invoke created function on each request
useFileRouter(req, res);
});
// 5. Start listening a server on 4000 port
const port = 4000;
server.listen(port, () =>
console.log(`Server running at http://localhost:${port}/`)
);
}
// 6. Run entry-point function
run();
A first route
We will create a home route that displays welcome content.
- Create an
api
folder at the root of your project.
├── api/ <-
├── server.js
└── package.json
- Create a file named
index.js
inside this folder:
├── api/
│ └── index.js <-
├── server.js
└── package.json
module.exports = function index(req, res) {
res.end("Welcome to our shop!");
}
- Run a server using:
node server.js
command - Open a browser and navigate to
http://localhost:4000
.
You should see the messageWelcome to our shop!
displayed.
Congratulations! 🎉 You've created a first file route
Add HTTP Methods
- Before we start, we need a small utility function which will parse json from a request.
Create a folder
utils
and puthttp.utils.js
file inside.
├── api/
├── ...
├── utils/
│ └── http.utils.js <-
...
module.exports = {
parseJson(request) {
return new Promise((resolve, reject) => {
let data = '';
request.on('data', (chunk) => {
data += chunk;
});
request.on('end', () => {
try {
const parsedData = JSON.parse(data);
resolve(parsedData);
} catch (e) {
reject(e);
}
});
});
}
}
- Create a folder called
products
and anindex.js
file inside it.
├── api/
│ ├── products/ <-
│ │ └── index.js <-
│ └── ...
...
- Implement
get
andpost
methods:
const { parseJson } = require('../../utils/http.utils');
module.exports = {
get: (req, res) => {
res.end('list of products');
},
post: async (req, res) => {
const newProduct = await parseJson(req);
res.end(`a product will be created: ${JSON.stringify(newProduct)}`);
}
}
-
Open a browser and go to http://localhost:4000/products.
You should see alist of products
message displayed. -
Make a POST request using
curl
,Postman
or any tool you like onhttp://localhost:4000/products
The response should displaya product will be created
along with your content.
Perfect! 🎉 Let's move on
Dynamic Routes
- Create a new file with the name
[id]
inside theproduct
folder.
├── api/
│ ├── products/
│ │ ├── ...
│ │ └── [id].js <-
│ └── index.js
...
- Fill it the same way as you did before:
module.exports = {
// Add the `routeParams` argument as the final argument to the function. This argument will contain
// all the taken route parameters.
get: (req, res, routeParams) => {
const { id } = routeParams;
res.end(`product ${id} info`);
}
};
- Open a browser and go to
http://localhost:4000/products/123
.
The page should display a message:product 123
.
Alright, let's make it more sophisticated.
Say, we want to address the following case:
/catalog/tag-1/tag-2/tag-n
- Create a
catalog
folder with[[...categories]].js
inside.
├── api/
│ ├── catalog/
│ │ ├── ...
│ │ └── [[...categories]].js
│ ├── index.js
...
And add a single get
method:
module.exports = {
get: (req, res, routeParams) => {
const { categories } = routeParams;
// This type of route also covers just "/catalog"
if (!categories) {
return res.end('all products');
}
res.end(`get products that have such tags: ${categories}`);
},
};
- Open a browser and go to
http://localhost:4000/catalog/men/sneakers/nike
.
The page should display a list of categories:'men','sneakers','nike'