How to organize Node.js code
Tags: node, javascript, architecture
Published: 2021-07-09 10:44:12

---
title: How to organize Node.js code
published: true
date: 2021-03-25 00:00:00 UTC
tags: node, javascript, architecture
canonical_url: https://www.mariokandut.com/how-to-organize-code-into-modules-in-node-javascript/
---

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](https://www.mariokandut.com/how-does-the-node-js-module-system-work/).

## [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#code-example)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
```

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.

## [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#tldr)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](https://www.twitter.com/mariokandut)**.

If you want to know more about **[Node](https://www.mariokandut.com/tags/node)**, have a look at these [Node Tutorials](https://www.mariokandut.com/tags/node).

### [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#references-and-big-thanks)References (and Big thanks):

[HeyNode](https://heynode.com/tutorial/organize-your-nodejs-code-modules/),[NodeJS - ESM](https://nodejs.org/api/esm.html#esm_modules_ecmascript_modules),[node-fetch](https://www.npmjs.com/package/node-fetch)