以下是如何按照之前讨论的组织结构对你的代码进行剥离和重构的完整示例。
文件结构
project-root-directory/
|-- bin/
| |-- www
|
|-- common/
| |-- MySQLConnector.ts
|
|-- routes/
| |-- index.ts
|
|-- package.json
|-- tsconfig.json
|-- app.ts
1. bin/www
在bin/
目录下,创建一个名为www
的文件,并添加以下内容:
#!/usr/bin/env node
import app from '../app';
import http from 'http';
const port = 3000;
app.set('port', port);
const server = http.createServer(app);
server.listen(port);
server.on('listening', () => {
console.log(`Server is running at http://localhost:${port}/`);
});
确保这个文件是可执行的(在Unix/Linux下,运行chmod +x bin/www
)。
2. common/MySQLConnector.ts
这个文件保持不变。
3. routes/index.ts
在routes/
目录下,创建一个名为index.ts
的文件,并添加以下内容:
import express from 'express';
import { MySQLConnector } from '../common/MySQLConnector';
const router = express.Router();
router.get('/', async (req, res) => {
const connector = new MySQLConnector();
try {
const connection = await connector.getConnection();
// Use the connection for database operations
const [rows] = await connection.execute('SELECT * FROM fb_user');
console.log('Query result:', rows);
// Release the connection when done
connector.releaseConnection(connection);
res.send('Hello TypeScript with Express!');
} catch (error) {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
}
});
export default router;
4. app.ts
最后,在app.ts
文件中,只包含与应用设置相关的代码,并导入路由:
import express from 'express';
import indexRouter from './routes/index';
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use('/', indexRouter);
export default app;
5. package.json
在package.json
文件的scripts
部分,你可以像这样更新dev
脚本:
{
"scripts": {
"dev": "nodemon --watch 'common/**/*' --watch 'routes/**/*' --watch 'bin/**/*' -e ts,tsx --exec ts-node bin/www"
}
}