How to organize Node.js code
© https://nodejs.org/en/

How to organize Node.js code

Maintainable Node.js code , easier to read and no code duplication.

By Mario Kandut

More articles:

nodejavascript

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.

💰 Start your cloud journey with $100 in free credits with DigitalOcean.

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.

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

More node articles:

How to handle binary data in Node.js?

How to use streams to ETL data?

How to connect streams with pipeline?

How to handle stream errors?

How to connect streams with pipe?

What Is a Node.js Stream?

Handling Errors in Node (asynchronous)

Handling Errors in Node.js (synchronous)

Introduction to errors in Node.js

Callback to promise-based functions

ETL: Load Data to Destination with Node.js

ETL: Transform Data with Node.js

ETL: Extract Data with Node.js

Event Emitters in Node.js

How to set up SSL locally with Node.js?

How to use async/await in Node.js

What is an API proxy?

How to make an API request in Node.js?

How does the Event Loop work in Node.js

How to wait for multiple Promises?

How to organize Node.js code

Understanding Promises in Node.js

How does the Node.js module system work?

Set up and test a .env file in Node

How to Use Environment Variables in Node

How to clean up node modules?

Restart a Node.js app automatically

How to update a Node dependency - NPM?

What are NPM scripts?

How to uninstall npm packages?

How to install npm packages?

How to create a package.json file?

What Is the Node.js ETL Pipeline?

What is data brokering in Node.js?

How to read and write JSON Files with Node.js?

What is package-lock.json?

How to install Node.js locally with nvm?

How to update Node.js?

How to check unused npm packages?

What is the Node.js fs module?

What is Semantic versioning?

The Basics of Package.json explained

How to patch an NPM dependency

What is NPM audit?

Beginner`s guide to NPM

Getting started with Node.js

Scroll to top ↑

We use cookies 🍪 to build a better website.! Close to accept or learn more.