대규모 Node.js 프로젝트를 구성하는 방법
대규모 Node.js 프로젝트를 구성하는 좋은 방법은 무엇입니까?
예를 들어, express.js와 socket.io를 모두 사용하는 앱? 여기에는 응용 프로그램 논리 구조와 파일 시스템이 모두 포함됩니다.
현재 저는 엄청난 양의 코드를 하나의 마스터 js 파일에 넣고 거대한 전역 객체에 코드를 배치하는 중입니다.
초보자의 예
나는 원래 @ david-ellis에서 확인한 것이 마음에 들며 좋은 것으로 이해하기 위해 깊이 연구해야합니다. 그러나 나는 간단한 예제를보고 싶어하는 초보자를 위해 더 단순화 된 것이 좋았을 것입니다. 누군가가 저에게 보여 주었으면 좋았을 것입니다.
express를 사용하고 app.js 파일에 많은 경로가 나열된 일반적인 시나리오를 제공하겠습니다. 그 내용은 다음과 같습니다.
app.js
// ... startup code omitted above
app.get('/', function(req, res) {
res.render('index', { title : 'home' });
});
app.get('/contactus', function(req, res) {
res.render('contactus', { title : 'contact us' });
});
app.get('/anotherpage', function(req, res) {
res.render('anotherpage', { title : 'another page' });
});
// and so on...
50 개의 라우트가 있다고 상상할 수 있습니다.이 파일은 손을 뗄 수 없습니다. app.js 파일에서 이러한 혼란을 제거하는 것이 좋습니다.
이제 앱에 "controllers"폴더를 만들어 구조가 다음과 같이 보이도록합니다.
app.js
/controllers
"/ controllers"내에 "index.js"라는 파일을 생성하고 다음 코드를 입력합니다.
/controllers/index.js
module.exports.set = function(app) {
// copy your routes listed in your app.js directly into here
}
"app.js"파일에서 경로 목록을 잘라내어 붙여넣고 "/controllers/index.js"파일에 배치합니다.
app.js 파일에서 경로를 제거하고 경로를 대신하여 다음을 수행하십시오.
app.js
// remove your routes and replace with this code
var controllers = require('./controllers');
controllers.set(app);
이제 "/controllers/index.js"파일도 분할되도록하려면 예제를 하나 더 추가하여 Node.js가 코드를 구성하는 방법에서 실제로 러시아 인형처럼 작동하는 방식을 살펴 보겠습니다.
"/ controllers"내에 "accounts.js"파일을 하나 더 추가하고 그 안에 다음을 배치합니다.
/controllers/account.js
module.exports.set = function(app) {
// put more app route listings here
}
이제 "/controllers/index.js 파일에"account.js "에 대한 참조를 입력하십시오.
/controllers/index.js
var account = require('./account.js');
module.exports.set = function(app) {
// your routes here
// let "account.js" set other routes
account.set(app);
}
당신이 상상할 수 있듯이, 당신은 계속해서 더 작고 작은 부분으로 나누고 폴더 안에 더 많은 폴더를 넣고 원한다면 "require"로 참조 할 수 있습니다. "/ lib"또는 라이브러리 파일에 동일한 개념을 사용할 수 있습니다. "node_modules"는 이미 이것을하고 있습니다.
이것이 node.js가 프로그래밍하기에 매우 즐거운 이유 중 하나 일뿐입니다.
관리 가능한 Express 4 라우팅 예
Here's another post I responded to about express 4 routes that relates to this.
Rest with Express.js nested router
I wrote a blog post about this very subject a few days ago, and although the article is in French, I set up a GitHub repo (in English) to show a working example of the structure I use.
Obviously, there is no definitive answer to this question, but it's interesting to see what others are doing, and I am all ears for other opinions on the subject (which was also discussed here, where you can see a summary of what I suggest).
Similar to the other blog post, I wrote one specifically about organizing Express
applications. It's the method I've been using for about a year and a half. Basically, organize your applications around your data entities or any other core elements. Place logic for each of those elements in their own directories. I tried to borrow a lot from Python.
http://rycole.com/2013/01/28/organizing-nodejs-express.html
His Articles are no longer online, but Eric Satterwhite's node series recommended a structure as listed below.
# Project
.
|-- packages/
| |-- project-core
| | |-- lib/
| | |-- commands/
| | |-- startup/
| | |-- conf/
| | |-- test/
| | |-- package.json
| | |-- README.md
| | |-- events.js
| | |-- .npmignore
| | `-- index.js
|-- package.json
`-- index.js
With the packages/
folder turning into your source for modularity.
If you are a beginner in this area, I suggest you take a look at existing projects that are loved by developers. Some of them are:
Sails.js - 18k stars. You can take a look how they organized APP structure at the link I provided. A great website has an explanation for each folder in the structure.
Express.js generator - 800 stars. There is the great and simple template to start working with Express.js. Here you can notice how they split routes from the app.
By the way, so many developers did your case before, and you can just fork it and upgrade.
Kioska. Look how they separate events into different files at the
events/
folder.Ballons.io 2.3k stars. Unfortunately, they have the whole socket server in one file but you can learn the whole structure of the app with node.js and socket.io
If you don't mind, you can always learn typescript and go for https://nestjs.com/
If you want to stick with JS I strongly recommend to use onion architecture. The best practice is to keep separated business logic, controllers, even libraries (they should be wrapped inside of some classes / helpers) - just in case, if you will have to migrate to another library (different CSV parser etc.).
With onion architecture, you don't care from where requests comes from, there won't be a lot of changes to add even some message broker.
Also try this one https://en.wikipedia.org/wiki/Domain-driven_design
ESLint may help with proper project organization.
참고URL : https://stackoverflow.com/questions/9832019/how-to-organize-large-node-js-projects
'Development Tip' 카테고리의 다른 글
.NET에는 기본 제공 EventArgs가 있습니까? (0) | 2020.10.05 |
---|---|
코드 우선 엔티티 프레임 워크에서 뷰를 사용하는 방법 (0) | 2020.10.05 |
스칼라 커링과 부분적으로 적용된 함수 (0) | 2020.10.05 |
AutoCompleteTextView를 사용하고 웹 API의 데이터로 채우려면 어떻게합니까? (0) | 2020.10.05 |
.append 후 jQuery 함수 (0) | 2020.10.05 |