該是來補這個坑了。
簡述
這篇學完後我應該要學到:
__dirname
,目前位置的資料夾路徑
__filename
,目前位置的檔案路徑
path.basename
,讀取路徑最後的資料夾 / 檔案的名稱
fs.readdirSync
,讀取資料夾底下的所有檔案 / 資料夾
path.join
拚路徑遊戲,填什麼就接什麼
總之廢話不多說,直接來看 code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| 'use strict';
const fs = require('fs'); const path = require('path'); const Sequelize = require('sequelize'); const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.js')[env]; const db = {};
let sequelize;
if (config.use_env_variable) { sequelize = new Sequelize(process.env[config.use_env_variable], config); } else { sequelize = new Sequelize(config.database, config.username, config.password, config); }
fs .readdirSync(__dirname) .filter(file => { return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); }) .forEach(file => { const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes); db[model.name] = model; });
Object.keys(db).forEach(modelName => { if (db[modelName].associate) { db[modelName].associate(db); } });
db.sequelize = sequelize; db.Sequelize = Sequelize;
module.exports = db;
|
看懂這份檔案後,我才知道環境變數到底怎麼調,不然實在是霧煞煞。