express.js 애플리케이션을 구성하는 방법은 무엇입니까?
Express.js 애플리케이션 app.js에서 파일 을 분할하고 모듈화하는 일반적인 규칙이 있습니까? 아니면 모든 것을 하나의 파일에 보관하는 것이 일반적입니까?
나는 다음과 같이 분해했다.
~/app
|~controllers
| |-monkey.js
| |-zoo.js
|~models
| |-monkey.js
| |-zoo.js
|~views
| |~zoos
| |-new.jade
| |-_form.jade
|~test
| |~controllers
| |-zoo.js
| |~models
| |-zoo.js
|-index.js
나는 수출을 사용하여 관련된 것을 반환합니다. 예를 들어, 내가하는 모델에서 :
module.exports = mongoose.model('PhoneNumber', PhoneNumberSchema);
전화 번호를 만들어야하는 경우 다음과 같이 간단합니다.
var PhoneNumber = require('../models/phoneNumber');
var phoneNumber = new PhoneNumber();
스키마를 사용해야하는 경우 PhoneNumber.schema
(이는 경로 폴더에서 작업하고 있으며 한 수준 위로 이동 한 다음 모델로 내려 가야한다고 가정)
4 편집
명시 위키는 그것의 상단에 내장 프레임 워크의 목록이 있습니다.
그중 트위터의 투우사 는 꽤 잘 구성되어 있다고 생각 합니다. 실제로 앱의 일부를로드하는 방법과 매우 유사한 접근 방식을 사용했습니다.
derby.js 도 매우 흥미로워 보입니다. 모든 과대 광고가없는 유성 과 비슷하며 실제로 신용이 필요한 곳에 신용을 부여합니다 (특히 노드 및 표현).
3 편집
CoffeeScript의 팬이고 (나는 아닙니다) Rails의 L & F를 원하신다면 Tower.js 도 있습니다 .
2 편집
Rails에 익숙하고 일부 개념의 블리드 오버에 신경 쓰지 않는다면 Locomotive가 있습니다. Express를 기반으로하는 경량 프레임 워크입니다. RoR과 매우 유사한 구조를 가지고 있으며 좀 더 기본적인 개념 (예 : 라우팅)을 전달합니다.
사용할 계획이 없더라도 확인해 볼 가치가 있습니다.
1 편집
nodejs-express-mongoose-demo 는 내가 구조화 한 방식과 매우 유사합니다. 확인 해봐.
경고 : 노드 녹아웃을 위해 함께 해킹 한 코드를 참조하면 작동하지만 우아하거나 세련되지는 않습니다.
분할에 대해 더 구체적으로 설명하기 app.js위해 다음 app.js 파일이 있습니다.
var express = require('express'),
bootstrap = require('./init/bootstrap.js'),
app = module.exports = express.createServer();
bootstrap(app);
이것은 기본적으로 모든 부트 스트랩을 별도의 파일에 배치 한 다음 서버를 부트 스트랩한다는 것을 의미합니다.
그렇다면 부트 스트랩 은 무엇을합니까?
var configure = require("./app-configure.js"),
less = require("./watch-less.js"),
everyauth = require("./config-everyauth.js"),
routes = require("./start-routes.js"),
tools = require("buffertools"),
nko = require("nko"),
sessionStore = new (require("express").session.MemoryStore)()
module.exports = function(app) {
everyauth(app);
configure(app, sessionStore);
less();
routes(app, sessionStore);
nko('/9Ehs3Dwu0bSByCS');
app.listen(process.env.PORT);
console.log("server listening on port xxxx");
};
모든 서버 초기화 설정을 멋진 덩어리로 나눕니다. 구체적으로 특별히
- everyauth를 사용하여 모든 원격 OAuth 인증을 설정하는 청크가 있습니다.
- 내 응용 프로그램을 구성하는 청크가 있습니다 (기본적으로 호출
app.configure) - 덜 펀치하는 코드가 약간 있으므로 런타임에 내 적은 것을 CSS로 다시 컴파일합니다.
- 내 모든 경로를 설정하는 코드가 있습니다.
- 나는 이것을 작은 nko 모듈이라고 부릅니다.
- Finally I start the server by listening to a port.
Just for example let's look at the routing file
var fs = require("fs"),
parseCookie = require('connect').utils.parseCookie;
module.exports = function(app, sessionStore) {
var modelUrl = __dirname + "/../model/",
models = fs.readdirSync(modelUrl),
routeUrl = __dirname + "/../route/"
routes = fs.readdirSync(routeUrl);
Here I load all my models and routes as arrays of files.
Disclaimer: readdirSync is only ok when called before you start the http server (before .listen). Calling synchronious blocking calls at server start time just makes the code more readable (it's basically a hack)
var io = require("socket.io").listen(app);
io.set("authorization", function(data, accept) {
if (data.headers.cookie) {
data.cookie = parseCookie(data.headers.cookie);
data.sessionId = data.cookie['express.sid'];
sessionStore.get(data.sessionId, function(err, session) {
if (err) {
return accept(err.message, false);
} else if (!(session && session.auth)) {
return accept("not authorized", false)
}
data.session = session;
accept(null, true);
});
} else {
return accept('No cookie', false);
}
});
Here I punch socket.io to actually use authorization rather then letting any tom and jack to talk to my socket.io server
routes.forEach(function(file) {
var route = require(routeUrl + file),
model = require(modelUrl + file);
route(app, model, io);
});
};
Here I start my routes by passing the relevant model into each route object returned from the route file.
Basically the jist is you organize everything into nice little modules and then have some bootstrapping mechanism.
My other project (my blog) has an init file with a similar structure.
Disclaimer: the blog is broken and doesn't build, I'm working on it.
For maintainable routing organisation you can check out this article about the express-routescan node module and try it. This is the best solution for me.
I have my apps build on top of the express-generator tool. You can install it by running npm install express-generator -g and run it using express <APP_NAME>.
To give you a perspective, one of my smaller application's structure looked like this:
~/
|~bin
| |-www
|
|~config
| |-config.json
|
|~database
| |-database.js
|
|~middlewares
| |-authentication.js
| |-logger.js
|
|~models
| |-Bank.js
| |-User.js
|
|~routes
| |-index.js
| |-banks.js
| |-users.js
|
|~utilities
| |-fiat-converersion.js
|
|-app.js
|-package.json
|-package-lock.json
One cool thing I like about this structure I end up adopting for any express application I develop is the way the routes are organized. I did not like having to require each route files into the app.js and app.use() each route, especially as the file gets bigger. As such, I found it helpful to group and centralize all my app.use() on a ./routes/index.js file.
In the end, my app.js will look something like this:
...
const express = require('express');
const app = express();
...
require('./routes/index')(app);
and my ./routes/index.js will look something like this:
module.exports = (app) => {
app.use('/users', require('./users'));
app.use('/banks', require('./banks'));
};
I am able to simply require(./users) because I wrote the users route using express.Router() which allows me to "group" multiple routes and then export them at once, with the goal of making the application more modular.
This is an example of what you would fine on my ./routers/users.js route:
const router = require('express').Router();
router.post('/signup', async (req, res) => {
// Signup code here
});
module.exports = router;
Hopefully this helped answer your question! Best of luck!
참고URL : https://stackoverflow.com/questions/7732293/how-to-structure-a-express-js-application
'Programing' 카테고리의 다른 글
| MySQL에 쓸 때 TextArea에서 줄 바꿈 유지 (0) | 2020.08.18 |
|---|---|
| XML은 대소 문자를 구분합니까? (0) | 2020.08.17 |
| ASP.NET MVC3 : packages.config의 용도는 무엇입니까? (0) | 2020.08.17 |
| Java 프로그램에서 다른 jar 실행 (0) | 2020.08.17 |
| 실제 세계에서 함수형 프로그래밍을 어떻게 사용할 수 있습니까? (0) | 2020.08.17 |