Maintainable Node.js code , easier to read and no code duplication.
Posted
Updated
Europe’s developer-focused job platform
Let companies apply to you
Developer-focused, salary and tech stack upfront.
Just one profile, no job applications!
This article is based on Node v16.14.0.
A Node.js application grows, and the code should be organized and maintainable, to achieve this, we have to separate the code into modules. Writing modular code also helps to reuse logic and functions without code duplication. If you want to learn more about the module system in Node.js, check out Node's Module System explained.
💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.
Creating modules helps organize the code, because related functionality is kept in a single place. Mixing together code with different functions into one large file, and code duplication in different places will be avoided.
For this example we are going to write an API proxy to retrieve todos from a placeholder API and transform it.
Create a project folder.
mkdir node-organize
Initialize project with npm init -y
to install node packages. Not required for using modules, but we are going to use node-fetch
.
cd node-organize
npm init -y
Install node-fetch
or axios
to make fetch requests.
npm install node-fetch
We are going to write code we reuse inside of a file that allows us to export the code at the end of the file. So the code blocks can be required elsewhere.
Create a services.js
file, which holds the reusable code blocks.
touch services.js
Now we can add the code to extract and transform the data.
// import fetch
const fetch = require('node-fetch');
// best practice to use constants for URLs
const URL = 'https://jsonplaceholder.typicode.com/todos';
/*
interface TodoItem {
userId: number;
id: number;
title: string;
completed: boolean;
}
Todos: Array<TodoItem>
*/
// fetch all todos and decode response as json
function getAllTodos() {
return fetch(URL)
.then(response => response.json())
.then(todos => todos)
.catch(err => console.err(err));
}
// filter todos
function filterCompleted(todos, completed) {
return todos.filter(i => i.completed === completed);
}
// filter todos per user id
function filterPerUserId(todos, id) {
return todos.filter(i => i.userId === id);
}
To export the code from the module, we override the module.exports
object with a new object containing the functions from services.js
.
module.exports = {
getAllTodos,
filterPerUserId,
filterCompleted,
};
Then create an index.js
file, which will import the modules.
touch index.js
Add imports and output todos.
const {
getAllTodos,
filterCompleted,
filterPerUserId,
} = require('./services');
// getAllTodos returns a Promise
getAllTodos().then(todos => {
const completed = filterCompleted(todos, true);
const userCompletedTodos = filterPerUserId(completed, 10);
console.log(userCompletedTodos);
});
Now, run the code with node index.js
and should see the todos as output in the console.
Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.
If you want to know more about Node, have a look at these Node Tutorials.
Never miss an article.