简体   繁体   中英

How do I properly modulate my code in a Node.JS project?

[TL;DR] Just read the bits in bold .

I'm pretty new to Node.JS but have been getting on fine building some working projects. Now I have a burning question that I have been Googling for about half an hour but all I can find is frustratingly light-touch tutorials that don't answer my question, so here I go...

I have a Node.JS project that uses the Express framework. The code for one of the routes is getting pretty big now, so naturally my instincts as a good programmer are to break it out into it's own Class or Module or Package or whatever it is to be called.... and here lies my problem. Where is the tutorial about the language around Node.JS and how does one go about carving up their own code into neatly modulated, easy-to-read chunks?

It seems that every guide out there goes like this...

  1. Create a NodeJS project
  2. Install an npm module to the project
  3. Add a single line route that calls the module
  4. Pat yourself on the back and start applying for jobs as a full-stack JavaScript developer.

It's doing my head in! I wanna get deep and dirty with some complicated bespoke code but I also want to do things in some proper, standardised way but I don't know what folders to create, how to nest them, what naming convention to follow or anything like that. Where's the Jeff Way for NodeJS?

Please, someone point me in the direction of a good tutorial or some documentation around this subject so I can continue my learning. Thanks in advance.

From the section headed "Code Organization" on An Absolute Beginner's Guide to Node.JS :

In most applications your code will be split into several files. There's no standard or enforced organization to what files go where. This isn't Rails. There's no concept of views go here and controllers go there. You can do whatever you want.

So there have it. This isn't Rails 😢 You can do whatever you want 😨

But looking at the accepted answer to another question on SO: Folder structure for a Node.js project we can see that a folder called controllers in the root of the project is a common location but also that the routes folder created when you use the Express Generator to bootstrap a new project is considered an alternative to this.

Summary: All things considered and inspired by both my experience using other MVC frameworks (eg. Laravel) and @programmingheadache's answer I am going to keep the routes folder but also create a controllers folder as well.

This way I can keep the routes folder specifically for defining the routing of the project and keep the logic separate in several files inside controllers . I follow the mantra that routing is documentation and I would hate for any future reviewers of my project to get bogged-down by logic when they are just trying to establish the early basics of what URIs exist and with what parameters.

What i usually do is is put my logic in controllers and reference them from the routes.js. eg: personController with a method find(id) and then in the routes.js put a route router.get('/:id', personController.find);

personcontroller:

module.exports = (app) => {
return { 
    find(req, res, next){
        const id = req.params.id
        //return a user
    } 
};

}

routes:

router.get('/:id', personController.find);

pass every error to next and use a middelware to handle them

greetings

Ian

For the

Please, someone point me in the direction of a good tutorial or some documentation around this subject so I can continue my learning. Thanks in advance.

part:

├───models
│   ├───user.model.js
├───routes
│   ├───user.route.js
├───services
│   ├───user.service.js
├───controllers
│   ├───user.controller.js

from https://riptutorial.com/node-js/example/32331/model-routes-controllers-services-directory-structure

and

src
│   app.js          # App entry point
└───api             # Express route controllers for all the endpoints of the app
└───config          # Environment variables and configuration related stuff
└───jobs            # Jobs definitions for agenda.js
└───loaders         # Split the startup process into modules
└───models          # Database models
└───services        # All the business logic is here
└───subscribers     # Event handlers for async task
└───types           # Type declaration files (d.ts) for Typescript

from https://softwareontheroad.com/ideal-nodejs-project-structure/

Project structure must be like :

-- app.js
-- server.js

config \\

--databaseConfig.js

--thirdPartyConfig.js

--appConfig.js

controllers \\

--userCtrl.js

--productCtrl.js

--businessCtrl.js

middlewares \\

--endpointHandler.js

--authHandler.js

--errorHandler.js

routes \\

--userRoute.js

--productRoute.js

--businessRoute.js

utils \\

--encryptFile.js

--uploadFile.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM