5 Fundamental Rules of a Node.js Project Structure

In these chapters, you can learn how to get started with Node.js and deliver software products using it.

nodeJS-frameworkMost Node.js frameworks don’t come with a fixed directory structure and it might be challenging to get it right from the beginning. In this tutorial, you will learn how to properly structure a Node.js project to avoid confusion when your applications start to grow.

There are a lot of possible ways to organize a Node.js project – and each of the known methods has their ups and downs.

However, according to our experience, developers always want to achieve the same things: clean code and the possibility of adding new features with ease.

You might also like…

We have outlined five simple guiding rules which we enforce during Node.js development. If you manage to follow them, your projects will be fine:

Rule 1 – Organize your Files Around Features, Not Roles

Imagine, that you have the following directory structure:

The problems with this approach are:

  • to understand how the product pages work, you have to open up three different directories, with lots of context switching,
  • you end up writing long paths when requiring modules: require('../../controllers/user.js')

Instead of this, you can structure your Node.js applications around product features / pages / components. It makes understanding a lot easier:

Rule 2 – Don’t Put Logic in index.js Files

Use these files only to export functionality, like:

Rule 3 – Place Your Test Files Next to The Implementation

Tests are not just for checking whether a module produces the expected output, they also document your modules (you will learn more on testing in the upcoming chapters). Because of this, it is easier to understand if test files are placed next to the implementation.

Put your additional test files to a separate test folder to avoid confusion.

Rule 4 – Use a config Directory

To place your configuration files, use a config directory.

Rule 5 – Put Your Long npm Scripts in a scripts Directory

Create a separate directory for your additional long scripts in package.json

Next up

You may also like...

Read previous post:
JavaScript Data Chart Libraries
10 Useful JavaScript Data Chart Libraries

There’s no doubt that JavaScript is the king of frontend scripting. It’s a fascinating language to create visual effects without...