
Security News
GitHub Actions Checkout Now Blocks Risky pull_request_target Checkouts
GitHub Actions checkout now blocks risky pull_request_target checkouts by default to help prevent pwn request supply chain attacks.
huxy-node-server
Advanced tools
一个精炼、高性能的 Express.js 服务器模板,为现代 Node.js 应用程序设计,提供灵活的功能和最佳实践。
"type": "module" 完全支持 ES Modules/health 端点,监控服务器状态.env 文件--watch 模式,自动重载代码# 通过 npm 安装
npm install huxy-node-server
# 或者通过 yarn 安装
yarn add huxy-node-server
# 或者通过 pnpm 安装
pnpm add huxy-node-server
import { startServer } from 'huxy-node-server';
// 启动服务器
const { app, config, httpServer } = await startServer({
port: 3000,
host: '0.0.0.0',
basepath: '/webui',
// 其他配置...
}, (config, app, httpServer) => {
// 可以在这里添加自定义路由
app.get('/hello', (req, res) => {
res.json({ message: 'Hello World!' });
});
});
const options = {
key: '/path/to/name.key',
cert: '/path/to/name.pem',
};
startServer({
port: 3000,
host: '0.0.0.0',
ssl: options,
});
import { startStatic } from 'huxy-node-server';
// 启动静态文件服务器
const server = await startStatic({
port: 9000,
basepath: '/',
buildPath: './dist', // 静态文件目录
});
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
port | number | 3000 | 服务器端口 |
host | string | '0.0.0.0' | 服务器主机 |
basepath | string | '/' | 基础路径前缀 |
apiPrefix | string | '/api' | API前缀 |
nodeEnv | string | 'development' | 运行环境 |
appName | string | 'HuxyServer' | 应用名称 |
{
helmet: {
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'"],
imgSrc: ["'self'", "data:", "https:"]
}
},
crossOriginEmbedderPolicy: false
}
}
{
cors: {
origin: ['http://example.com', 'http://localhost:3000'], // 或 '*'
credentials: true
}
}
{
rateLimit: {
windowMs: 900000, // 15 分钟
limit: 100, // 每个窗口内最大请求数
message: {
error: '请求过于频繁,请稍后再试'
}
}
}
{
logLevel: 30, // 日志级别 (10=trace, 20=debug, 30=info, 40=warn, 50=error, 60=fatal)
}
可以通过环境变量配置服务器:
# .env 文件
NODE_ENV=production
PORT=3000
HOST=0.0.0.0
BASEPATH=/
API_PREFIX=/api
CORS_ORIGIN=http://example.com,http://localhost:3000
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
LOG_LEVEL=30
或者通过命令行参数:
node server.js port=3000 host=localhost
.
├── src/
│ ├── app.js # Express 应用配置
│ ├── config.js # 默认配置
│ ├── server.js # 服务器启动逻辑
│ ├── routes.js # 默认路由
│ ├── middleware.js # 中间件集合
│ ├── logger.js # 日志系统
│ ├── utils.js # 工具函数
│ ├── staticServer.js # 静态文件服务器
│ └── resolvePath.js # 路径解析工具
├── example.js # 使用示例
└── package.json
import { startServer } from 'huxy-node-server';
import customMiddleware from './customMiddleware';
const { app } = await startServer({
port: 3000,
}, (config, app) => {
// 添加自定义中间件
app.use(customMiddleware);
// 添加自定义路由
app.get('/custom', (req, res) => {
res.json({ custom: 'route' });
});
});
import { startServer } from 'huxy-node-server';
const { app } = await startServer({
port: 3000,
}, (config, app) => {
// 添加自定义错误处理
app.use((err, req, res, next) => {
if (err instanceof CustomError) {
res.status(400).json({ error: err.message });
} else {
next(err);
}
});
});
import { startServer, createLogger } from 'huxy-node-server';
const customLogger = createLogger('custom-module', {
level: 'debug',
transport: {
target: 'pino-pretty',
options: { colorize: true }
}
});
customLogger.info('自定义日志消息');
import { startServer } from 'huxy-node-server';
import mongoose from 'mongoose';
const { app } = await startServer({
port: 3000,
}, async (config, app) => {
// 连接到 MongoDB
await mongoose.connect(config.DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// 添加数据库中间件
app.use((req, res, next) => {
req.db = mongoose.connection;
next();
});
// 添加 API 路由
app.get('/api/users', async (req, res) => {
const users = await req.db.collection('users').find().toArray();
res.json({ success: true, data: users });
});
});
startServer(config, callback)启动 Express 服务器
参数:
config (Object): 服务器配置对象callback (Function): 可选的回调函数,在服务器启动后调用返回: Promise<{app, config, httpServer}>
startStatic(config, callback)启动静态文件服务器
参数:
config (Object): 服务器配置对象callback (Function): 可选的回调函数,在服务器启动后调用返回: Promise<{app, config, httpServer}>
createLogger(name, customConfig)创建自定义日志实例
参数:
name (String): 日志实例名称customConfig (Object): 自定义配置返回: Pino 日志实例
logger默认日志实例
dateTime(): 获取当前时间字符串localIPs(): 获取本地 IP 地址列表nodeArgs(): 解析命令行参数getEnvConfig(): 获取环境变量配置checkPort(): 检查端口是否可用resolvePath(): 解析文件路径永远不要在代码中硬编码敏感信息,使用环境变量:
# .env 文件
JWT_SECRET=your_secret_key_here
DATABASE_URL=your_database_url
在生产环境中,始终使用 HTTPS。可以使用反向代理(如 Nginx)或直接配置:
import https from 'https';
import fs from 'fs';
const options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
};
https.createServer(options, app).listen(443);
根据您的应用需求调整速率限制:
{
rateLimit: {
windowMs: 15 * 60 * 1000, // 15 分钟
limit: 100, // 每个 IP 每个窗口内最大请求数
message: '太多请求,请稍后再试'
}
}
在生产环境中,限制 CORS 来源:
{
cors: {
origin: ['https://yourdomain.com', 'https://yourapp.com'],
credentials: true
}
}
根据需要调整 Helmet 配置:
{
helmet: {
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", "https://cdn.example.com"],
// 其他 CSP 指令...
}
}
}
}
# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY . .
EXPOSE 3000
CMD ["node", "src/index.js"]
构建并运行:
docker build -t huxy-server .
docker run -p 3000:3000 -d huxy-server
# 安装 PM2
npm install -g pm2
# 启动服务
pm2 start src/index.js --name huxy-server
# 保存进程列表
pm2 save
# 设置开机启动
pm2 startup
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
MIT © ahyiru
欢迎贡献!请遵循以下步骤:
git checkout -b feature/AmazingFeature)git commit -m 'Add some AmazingFeature')git push origin feature/AmazingFeature)如果您有任何问题或建议,请通过以下方式联系:
✨ Huxy Node Server - 为现代 Web 应用程序提供强大、可靠的后端解决方案!
FAQs
一个精炼、高性能的 Express.js 服务器模板,为现代 Node.js 应用程序设计,提供灵活的功能和最佳实践。
The npm package huxy-node-server receives a total of 30 weekly downloads. As such, huxy-node-server popularity was classified as not popular.
We found that huxy-node-server demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
GitHub Actions checkout now blocks risky pull_request_target checkouts by default to help prevent pwn request supply chain attacks.

Product
Socket now supports Custom Roles and Repository Access Permissions so organizations can control who can access specific repositories and actions.

Product
Socket MCP now lets AI assistants review org alerts, investigate threats using the Socket threat feed, and inspect package files in addition to dependency scoring.