DEV Community

Mario
Mario

Posted on • Originally published at mariokandut.com on

How to organize Node.js code

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.

Code Example

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Install node-fetch or axios to make fetch requests.

npm install node-fetch
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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,
};
Enter fullscreen mode Exit fullscreen mode

Then create an index.js file, which will import the modules.

touch index.js
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

Now, run the code with node index.js and should see the todos as output in the console.

TL;DR

  • Organizing code into modules results in easier maintainable code, it is easier to reuse code and it removes code duplication.

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.

References (and Big thanks):

HeyNode,NodeJS - ESM,node-fetch

Top comments (0)