我使用express.js作爲網絡服務器,並希望一個簡單的方法來分離所有的「app.get」和「app.post」函數來分離文件。例如,如果我想爲登錄頁面指定get和post函數,我想在動態加載的routes文件夾中有一個login.js文件(將自動添加所有文件,而不必指定每個文件)當我運行節點app.js動態加載路由與express.js
我試過這個this solution!,但它不適合我。
我使用express.js作爲網絡服務器,並希望一個簡單的方法來分離所有的「app.get」和「app.post」函數來分離文件。例如,如果我想爲登錄頁面指定get和post函數,我想在動態加載的routes文件夾中有一個login.js文件(將自動添加所有文件,而不必指定每個文件)當我運行節點app.js動態加載路由與express.js
我試過這個this solution!,但它不適合我。
app.js
var express=require("express");
var app=express();
var fs=require("fs");
var routePath="./routers/"; //add one folder then put your route files there my router folder name is routers
fs.readdirSync(routePath).forEach(function(file) {
var route=routePath+file;
require(route)(app);
});
app.listen(9123);
我已經把下面兩個路由器文件夾中
route1.js
module.exports=function(app){
app.get('/',function(req,res){
res.send('/ called successfully...');
});
}
route2.js
module.exports=function(app){
app.get('/upload',function(req,res){
res.send('/upload called successfully...');
});
}
@anonymousfox你還有什麼困難讓我知道。 – sachin
謝謝@sachin的幫助。我設法找到了一些工作,但與您提供的解決方案有點不同。當我嘗試將相對路徑「./routers/」傳遞給fs.readdirSync時,我收到一條錯誤,指出該目錄不存在。如果我做了同樣的事情,但使用了__dirname +「/ routes」,它能夠工作。我遇到的第二個問題是,mac osx在我的routes文件夾中創建了.DS_Store文件。當路由被添加時,這個文件正在被解析,並最終引發錯誤。爲了解決這個問題,我添加了一個檢查來查看是否存在.js分機。 – anonymousfox
我結束了採用遞歸的方法來解決P中的代碼可讀性和異步:
// routes
processRoutePath(__dirname + "/routes");
function processRoutePath(route_path) {
fs.readdirSync(route_path).forEach(function(file) {
var filepath = route_path + '/' + file;
fs.stat(filepath, function(err,stat) {
if (stat.isDirectory()) {
processRoutePath(filepath);
} else {
console.info('Loading route: ' + filepath);
require(filepath)(app, passport);
}
});
});
}
這可以由通過檢查來回回正確的文件擴展名等更強大的,但我把我的路線文件夾乾淨,不希望增加的複雜性
通過這種方法,不需要手動編寫路由。只需設置一個目錄結構,如URL路徑。路由示例爲/routes/user/table/table.get.js
,API路由爲/user/table
。
import app from './app'
import fs from 'fs-readdir-recursive'
import each from 'lodash/each'
import nth from 'lodash/nth'
import join from 'lodash/join'
import initial from 'lodash/initial'
const routes = fs(`${__dirname}/routes`)
each(routes, route => {
let paths = route.split('/')
// An entity has several HTTP verbs
let entity = `/api/${join(initial(paths), '/')}`
// The action contains a HTTP verb
let action = nth(paths, -1)
// Remove the last element to correctly apply action
paths.pop()
action = `./routes/${join(paths, '/')}/${action.slice(0, -3)}`
app.use(entity, require(action))
})
舉例路線:
import { Router } from 'express'
import Table from '@models/table.model'
const routes = Router()
routes.get('/', (req, res, next) => {
Table
.find({user: userIdentifier})
.select('-user')
.lean()
.then(table => res.json(table))
.catch(error => next(error))
})
module.exports = routes
鏈接的解決方案看起來像它應該工作;你能粘貼你的實現嗎? – furydevoid