Tips for organizing your NodeJS application into separate modules

After gaining some knowledge about NodeJS, I am now eager to develop a large enterprise application using it. However, I am uncertain about how to properly structure the project. Having experience with languages like PHP and Java, my initial thought is to segment the project into different NPM modules such as @mybigproject/customer, @mybigproject/cart, @mybigproject/checkout, etc.

The dilemma lies in the fact that these submodules would be installed in the node_modules folder of the application skeleton. How do I notify Express, for instance, about the location of template files within different module directories? Also, if I use TypeORM for data access, each submodule would have its own set of models. How can these models access the database configuration information which is present only in the main application skeleton? Conversely, how should the application skeleton know where to locate these models?

Answer №1

Avoid using npm modules for various sections of your project.

These components are critical parts of your project and often rely on your global configuration, schema, routing, etc.

Instead, separate them into different files and require them only where necessary.

You can take inspiration for folder structure from platforms like Sail.JS

Reserve the use of npm modules for creating utilities that will benefit multiple applications or when you need a simple way to update the utility code across all apps (or if you wish to share it as open source with others).

Answer №2

NPM has the capability to install a local folder as a dependency within your project. (source)

  • npm install <folder>:

When you run this command, the package located in the specified directory is installed as a symbolic link in your current project. Its dependencies will be installed before it gets linked. If the folder exists at the root of your project, its dependencies might get included in the top-level node_modules folder just like other types of dependencies.

Once installed, your module remains in its original location while a symlink with the same name as the module's folder is created within the top-level node_modules directory.

In these customized sub-modules, you have the ability to utilize __dirname and relative paths for accessing configuration files that can be used by databases or other data consumers.

It's important to note that sub-modules often function as utility components for the main module and should operate independently from the overall project context.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mongoose: The Model.aggregate function is returning an array with no elements

I'm currently working on a task to determine the average value using the user's review rating for a specific product. Here are my Schemas: const journalSchema = new mongoose.Schema({ title: String, category: String, subcategory: String, ...

Display a complete inventory of installed typings using the tsd command

How can I display a list of all installed tsd typings in the terminal? Perhaps using the following command: $ tsd list ...

unable to save the information to mongoDB

I've been attempting for the past 3 hours to save data from an HTML form to MongoDB using Node.js. When I click submit, it redirects to another page displaying the submitted data in JSON format, but it's not getting stored in the database. Here ...

The deployed software will not be able to send or receive any data

I'm facing an issue with my Angular app connected to a Node.js server, hosted on A2 hosting service. This problem has persisted for several weeks now. The website is currently unable to post or get any data. Local Node version: 14.15.4 Apache Server ...

Webpack: Live reloading is not functioning properly, however the changes are still successfully compiling

Could someone help me understand why my React application, set up with Webpack hot reload, is not functioning properly? Below is the content of my webpack.config.js: const path = require('path'); module.exports = { mode: 'development&apo ...

swagger: Request body not permitted

I am having trouble setting up a post endpoint using swagger because the requestBody parameter is not being allowed: /names/{roster}: get: #... post: x-swagger-router-controller: names description: Add or remove names ope ...

Converting basic text into JSON using Node.js

Today I am trying to convert a text into JSON data. For example: 1 kokoa#0368's Discord Profile Avatar kokoa#0000 826 2 Azzky 陈东晓#7475's Discord Profile Avatar Azzky 陈东晓#0000 703 3 StarKleey 帅哥#6163's Di ...

The fake class constructor being spied on by Sinon.js falsely returns a negative result, despite being invoked

Today marks my first attempt at using sinon.js, and here is a snippet of code that I am currently testing: class CustomError extends Error { constructor(code, message, err) { super(message); this.code = code; this.error = err; ...

Express and Mongoose Server Crash resulted in an ERR_HTTP_HEADERS_SENT issue

Currently, I am developing a user authentication backend using express and mongoose. My main focus right now is enabling users to update their name and email address. To achieve this, I am implementing a system where the email input is cross-checked with ...

Is it necessary to add the objectid to both schemas in mongodb?

I'm currently puzzled by whether I should push the objectId to both schemas or just save it in one of them. Here is my Schema setup: var CourseSchema = Schema({ title: String, content: [{ type: Schema.Types.ObjectId, ref: 'Video'}] ...

Having trouble launching a node application from a different folder location

I am encountering an issue with my MVC application using Node.js/Express. When I start the app using PM2 within a specific directory, everything works fine. However, if I try to start it from another directory, the app seems to start but then complains th ...

What is the best way to utilize functions in Express to dynamically display content on my Jade template?

I have successfully implemented a user registration and login page, but now I need to determine what content to display based on whether the user is logged in. I found this solution: app.use(function(req, res, next) { db.users.find({rememberToken: req.c ...

What is the process for sending an HTTP request within the Dialogflow -> Fulfillment environment?

When it comes to interacting with the API of my website to rectify the response for Google Assistant, I am facing some difficulties. 'use strict'; var requestNode = require('request'); const functions = require('firebase-function ...

Step-by-step guide on creating a Discord bot that automatically responds to all messages sent

Having some trouble with this code. The bot seems to only respond to stickers and pictures that are sent locally, but not text messages. Here is the code snippet: const Discord = require('discord.js'); const bot = new Discord.Client(); const t ...

Changing the req.path property within an expressjs middleware

I'm currently in the process of developing a middleware that will help eliminate locale strings from the path, such as /de/about becoming /about. This project is being implemented using express. To achieve this, I initially tried out the following mid ...

How to exclude a field in a mongoose query?

Within my User model, I have properties such as name, password, resetToken, and resetTokenExp. Whenever querying a user (using findById, find({}), etc.), I want to exclude the password, resetToken, and resetTokenExp fields. User.findById(id) .select(&a ...

Sort activities according to the preferences of the user

This is the concept behind my current design. Click here to view the design When making a GET request, I retrieve data from a MongoDB database and display it on the view. Now, I aim to implement a filter functionality based on user input through a form. ...

Creating route paths within a single .js file

I'm a beginner when it comes to Node/Express, and I have a question about my app structure. Here is a simplified version of how my app is set up: /app /routes filter.js index.js app.js In my app.js file, I have defined my routes like th ...

Utilizing Node.js to create a REST API that allows for seamless communication with a MongoDB database through

Currently, I am developing a web application utilizing the MERN framework (MongoDB, Express, Node.js for back-end, React for front-end). One specific part of my web application requires frequent access to a collection in the MongoDB database (every 50 ms) ...

Emit a broadcast message using Socket.io, excluding the socket ID of the current user

I'm currently working on a real-time application using socket.io Every time a user accesses the application, a unique socket ID is generated. Therefore, if I open the application in multiple browser tabs, each tab will have its own socket ID. To org ...