2025最新Sails.js入门指南:从安装到部署完整教程
【免费下载链接】sails Realtime MVC Framework for Node.js 项目地址: https://gitcode.com/gh_mirrors/sa/sails
你还在为Node.js后端开发选择合适的框架吗?想快速构建实时应用却被复杂配置困扰?本文将带你从零开始掌握Sails.js——这个被誉为"Node.js界的Rails"的全栈MVC框架。读完本文,你将能够:
- 快速搭建Sails.js开发环境
- 创建并配置数据模型与路由
- 实现实时功能与数据库交互
- 完成应用部署的全流程
Sails.js简介
Sails.js是一个基于Node.js的实时MVC框架,它借鉴了Ruby on Rails的架构思想,同时支持现代数据驱动的Web应用和API开发。特别适合构建聊天应用等实时功能。Sails.js构建在Express和Socket.io之上,提供了开箱即用的WebSocket支持和强大的ORM系统Waterline。

安装与环境配置
系统要求
- Node.js 10.x或更高版本
- npm 6.x或更高版本
安装Sails.js
# 全局安装Sails.js
npm install sails -g
官方安装指南:README.md
创建第一个Sails项目
新建项目
# 创建新项目
sails new my-app
# 进入项目目录
cd my-app
启动应用
# 启动开发服务器
sails lift
成功启动后,访问http://localhost:1337即可看到Sails.js的欢迎页面。Sails会自动创建项目结构,包括配置文件、控制器、模型和视图等目录。
数据模型(Model)创建
模型代表一组结构化数据,通常对应数据库中的表或集合。在Sails中,模型定义在api/models/目录下。
创建模型示例
// api/models/Product.js
module.exports = {
attributes: {
name: { type: 'string', required: true },
price: { type: 'number', required: true },
description: { type: 'string' },
inStock: { type: 'boolean', defaultsTo: true }
}
};
模型定义详情:Models.md
模型查询示例
// 在控制器中使用模型
async function getProducts(req, res) {
try {
const products = await Product.find({ inStock: true })
.sort('price ASC')
.limit(10);
return res.json(products);
} catch (err) {
return res.serverError(err);
}
}
路由(Routes)配置
路由用于将URL映射到相应的控制器动作或视图。Sails中的路由定义在config/routes.js文件中。
基本路由配置
// config/routes.js
module.exports.routes = {
// GET请求路由到视图
'GET /products': { view: 'products/list' },
// POST请求路由到控制器动作
'POST /products': { action: 'product/create' },
// 动态路由参数
'GET /products/:id': { action: 'product/show' }
};
路由配置详情:Routes.md
路由类型
- 自定义路由:手动配置的显式路由
- 蓝图路由:自动生成的RESTful API路由
- 资产路由:自动处理静态资源的路由
控制器(Actions)开发
控制器包含处理请求的业务逻辑,在Sails中称为"Actions",存放在api/controllers/目录下。
控制器示例
// api/controllers/product/create.js
module.exports = {
friendlyName: '创建产品',
description: '创建新产品并保存到数据库',
inputs: {
name: { type: 'string', required: true },
price: { type: 'number', required: true },
description: { type: 'string' }
},
exits: {
success: { responseType: 'ok' },
invalid: { responseType: 'badRequest' }
},
fn: async function (inputs, exits) {
try {
const newProduct = await Product.create({
name: inputs.name,
price: inputs.price,
description: inputs.description
}).fetch();
return exits.success(newProduct);
} catch (err) {
return exits.invalid({ error: err.message });
}
}
};
实时功能实现
Sails.js内置Socket.io支持,使实时功能开发变得简单。
服务器端设置
// api/controllers/chat/join.js
module.exports = {
fn: async function (inputs, exits) {
const roomName = inputs.room;
const userId = this.req.session.userId;
// 将用户加入房间
sails.sockets.join(this.req, roomName);
// 广播用户加入信息
sails.sockets.broadcast(roomName, 'userJoined', {
userId: userId,
room: roomName,
timestamp: new Date()
});
return exits.success();
}
};
客户端代码
// 连接到Sails服务器
const socket = io.connect('http://localhost:1337');
// 加入聊天房间
socket.get('/chat/join', { room: 'general' }, (response) => {
console.log('Joined chat room');
});
// 监听消息
socket.on('userJoined', (data) => {
console.log(`User ${data.userId} joined room ${data.room}`);
});
数据库集成
Sails.js的ORM系统Waterline支持多种数据库,包括MySQL、PostgreSQL、MongoDB等。
配置数据库连接
// config/datastores.js
module.exports.datastores = {
default: {
adapter: 'sails-mysql',
url: 'mysql://user:password@localhost:3306/myappdb'
}
};
数据库适配器列表:Available Adapters
应用部署
准备部署
# 设置生产环境
export NODE_ENV=production
# 安装生产依赖
npm install --production
部署选项
- 传统服务器部署:直接在服务器上运行
sails lift - 进程管理:使用PM2等工具管理应用进程
# 使用PM2启动应用 pm2 start app.js --name "my-sails-app" - 容器化部署:使用Docker容器化应用
总结
Sails.js提供了一个强大的框架,让Node.js开发变得更加高效。通过本文的介绍,你已经了解了Sails.js的基本概念和使用方法,包括:
- 项目创建与配置
- 数据模型与数据库交互
- 路由与控制器开发
- 实时功能实现
- 应用部署流程
更多高级功能和最佳实践,请参考官方文档:docs/concepts
扩展学习资源
- 官方文档:docs/
- 教程集合:docs/tutorials/tutorials.md
- 升级指南:docs/upgrading/upgrading.md
- API参考:docs/reference/reference.md
希望本指南能帮助你快速上手Sails.js开发。如有任何问题,欢迎参与Sails.js社区讨论!
【免费下载链接】sails Realtime MVC Framework for Node.js 项目地址: https://gitcode.com/gh_mirrors/sa/sails
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



