0
# Sails.js
1
2
**Sails.js** is an API-driven framework for building realtime Node.js web applications using MVC conventions. Built on top of Express.js and Socket.io, Sails provides a robust foundation for creating scalable web APIs and full-stack applications with automatic REST API generation, real-time communication, and a flexible hook system.
3
4
## Package Information
5
6
**Package Name**: `sails`
7
**Version**: 1.5.15
8
**License**: MIT
9
**Homepage**: https://sailsjs.com
10
11
**Node.js Support**: >= 0.10.0
12
**NPM Support**: >= 1.4.0
13
14
**Installation**:
15
```bash
16
npm install sails -g
17
```
18
19
## Core Imports
20
21
### CommonJS (Default)
22
```javascript
23
// Get the singleton Sails instance
24
const sails = require('sails');
25
26
// Get the Sails constructor for creating new instances
27
const Sails = require('sails').Sails;
28
// or
29
const Sails = require('sails').constructor;
30
31
// Create a new app instance
32
const app = new Sails();
33
```
34
35
### ESM (ES6 Modules)
36
```javascript
37
import sails from 'sails';
38
import { Sails } from 'sails';
39
40
// Create new instance
41
const app = new Sails();
42
```
43
44
## Basic Usage
45
46
### Creating and Starting a Sails Application
47
48
```javascript
49
const sails = require('sails');
50
51
// Lift the Sails application
52
sails.lift({
53
port: 3000,
54
environment: 'development'
55
}, (err) => {
56
if (err) throw err;
57
console.log('Sails app lifted successfully!');
58
});
59
```
60
61
### Basic Route Definition
62
```javascript
63
const sails = require('sails');
64
65
// Define routes programmatically
66
sails.get('/hello', (req, res) => {
67
return res.json({ message: 'Hello, World!' });
68
});
69
70
sails.post('/users', 'UserController.create');
71
72
// Lift the application
73
sails.lift();
74
```
75
76
## Architecture
77
78
Sails.js follows a modular architecture built around several key components:
79
80
### Core Components
81
82
- **Application Lifecycle**: Methods for starting, stopping, and managing the app lifecycle
83
- **HTTP Router**: Flexible routing system supporting REST conventions and custom routes
84
- **Actions System**: Controller actions and standalone action functions
85
- **Hook System**: 18+ built-in hooks providing core functionality (HTTP, sessions, security, etc.)
86
- **Configuration**: Unified configuration system with environment-specific settings
87
- **CLI Tools**: 16+ command-line tools for development and deployment
88
89
### MVC Pattern
90
- **Models**: Data layer with ORM integration (typically Waterline)
91
- **Views**: Template rendering with multiple engine support
92
- **Controllers**: Request handling and business logic
93
94
### Extension Points
95
- **Custom Hooks**: Extend Sails functionality through the hook system
96
- **Services**: Global utility functions and business logic
97
- **Policies**: Middleware for authorization and request preprocessing
98
- **Helpers**: Reusable utility functions with machine-based interfaces
99
100
## Application Lifecycle
101
102
The Sails application lifecycle is managed through core methods that handle startup, shutdown, and configuration:
103
104
```javascript { .api }
105
// Lift (start) the application
106
sails.lift(configOverride?: Dictionary, done?: Function): Sails
107
108
// Lower (stop) the application
109
sails.lower(options?: {delay?: Number, hardShutdown?: Boolean}, cb?: Function): void
110
111
// Load app without starting servers (internal)
112
sails.load(configOverride?: Dictionary, cb?: Function): void
113
```
114
115
**Key Features**:
116
- Graceful startup and shutdown sequences
117
- Configuration override support
118
- Event-driven lifecycle with 'lifted' and 'lower' events
119
- Child process management and cleanup
120
121
[Application Lifecycle](./application-lifecycle.md)
122
123
## HTTP Routing
124
125
Sails provides a powerful routing system that supports both programmatic and configuration-based route definitions:
126
127
```javascript { .api }
128
// HTTP method routing
129
sails.get(path: String, action: String|Function): Sails
130
sails.post(path: String, action: String|Function): Sails
131
sails.put(path: String, action: String|Function): Sails
132
sails.delete(path: String, action: String|Function): Sails
133
sails.all(path: String, action: String|Function): Sails
134
135
// Router instance methods
136
sails.router.bind(path: String|RegExp, bindTo: String|Object|Function, verb?: String, options?: Dictionary): void
137
sails.router.flush(routes?: Dictionary): void
138
sails.router.reset(): void
139
```
140
141
**Key Features**:
142
- RESTful routing conventions
143
- Route parameter extraction and validation
144
- Middleware chaining and policies
145
- Blueprint route auto-generation
146
147
[HTTP Routing](./routing.md)
148
149
## Actions System
150
151
Sails uses a flexible action system for handling requests, supporting both traditional controller methods and standalone action functions:
152
153
```javascript { .api }
154
// Action management
155
sails.registerAction(action: Function|Dictionary, identity: String, force?: Boolean): void
156
sails.getActions(): Dictionary
157
sails.reloadActions(cb?: Function): void
158
159
// Route discovery
160
sails.getRouteFor(target: String|Dictionary): {url: String, method: String}
161
sails.getUrlFor(target: String|Dictionary): String
162
```
163
164
**Key Features**:
165
- Machine-compatible action definitions
166
- Dynamic action registration and reloading
167
- Route-to-action mapping and discovery
168
- Input validation and output formatting
169
170
[Actions System](./actions.md)
171
172
## Built-in Hooks
173
174
Sails includes 18+ built-in hooks that provide core framework functionality:
175
176
```javascript { .api }
177
// Hook lifecycle (for custom hooks)
178
Hook.defaults(): Dictionary
179
Hook.configure(): void
180
Hook.loadModules(cb: Function): void
181
Hook.initialize(cb: Function): void
182
```
183
184
**Core Hooks**:
185
- **HTTP**: Server management and middleware
186
- **Blueprints**: Automatic REST API generation
187
- **Security**: CORS and CSRF protection
188
- **Session**: Session management and stores
189
- **Views**: Template engine integration
190
- **Logger**: Logging system setup
191
- **Services**: Service auto-loading
192
- **Policies**: Policy enforcement
193
- **I18n**: Internationalization support
194
195
[Built-in Hooks](./hooks.md)
196
197
## Configuration System
198
199
Sails provides a unified configuration system that merges settings from multiple sources:
200
201
```javascript { .api }
202
// Configuration access
203
sails.getRc(namespace?: String): Dictionary
204
sails.config: Dictionary
205
```
206
207
**Configuration Sources** (in order of precedence):
208
1. Command-line arguments
209
2. Environment variables (SAILS_*)
210
3. Local .sailsrc files
211
4. Global .sailsrc files
212
5. Default configuration
213
214
**Key Features**:
215
- Environment-specific configuration
216
- Configuration validation and normalization
217
- Runtime configuration access
218
219
[Configuration](./configuration.md)
220
221
## CLI Commands
222
223
Sails provides a comprehensive set of command-line tools for development and deployment:
224
225
```bash { .api }
226
# Core commands
227
sails new [path] # Create new Sails application
228
sails lift # Start the application
229
sails generate [type] # Generate code components
230
sails console # Interactive REPL with app context
231
232
# Development commands
233
sails debug # Start with debugger (Node v5-)
234
sails inspect # Start with inspector (Node v6+)
235
sails run [script] # Run custom scripts
236
237
# Utility commands
238
sails test # Run tests
239
sails www # Compile assets to www folder
240
sails upgrade # Upgrade Sails application
241
sails deploy # Deploy application
242
```
243
244
[CLI Commands](./cli.md)
245
246
## Events System
247
248
Sails inherits from EventEmitter and provides a rich event system for lifecycle management:
249
250
```javascript { .api }
251
// Core lifecycle events
252
sails.on('lifted', callback) // App successfully started
253
sails.on('lower', callback) // App shutdown initiated
254
sails.on('ready', callback) // App ready (internal)
255
256
// Router events
257
sails.on('router:before', callback) // Before route binding
258
sails.on('router:after', callback) // After route binding
259
sails.on('router:reset', callback) // Router reset
260
```
261
262
**Key Features**:
263
- Lifecycle event hooks
264
- Router event notifications
265
- Custom event support
266
- Hook-level event handling
267
268
[Events System](./events.md)
269
270
## Request Simulation
271
272
Sails provides built-in request simulation for testing and development:
273
274
```javascript { .api }
275
// Virtual request simulation
276
sails.request(opts: {url: String, method?: String, params?: Dictionary, headers?: Dictionary}, cb?: Function): MockClientResponse
277
sails.request(address: String, params?: Dictionary, cb?: Function): MockClientResponse
278
```
279
280
**Use Cases**:
281
- Unit and integration testing
282
- Development without HTTP server binding
283
- Internal service communication
284
285
## Key Constants and Utilities
286
287
```javascript { .api }
288
// Asset detection pattern
289
sails.LOOKS_LIKE_ASSET_RX: RegExp // /^[^?]*\/[^?\/]+\.[^?\/]+(\?.*)?$/
290
291
// Utility methods for debugging and serialization
292
sails.inspect(): String // Custom inspection output for console.log/util.inspect
293
sails.toString(): String // String representation of Sails app instance
294
sails.toJSON(): Dictionary // JSON-serializable summary of the app instance
295
296
// Development validation methods
297
sails.isLocalSailsValid(sailsPath: String, appPath: String): Boolean // Check if local Sails installation is valid
298
sails.isSailsAppSync(appPath: String): Boolean // Check if directory contains a valid Sails app
299
```
300
301
## Getting Started
302
303
1. **Install Sails globally**: `npm install -g sails`
304
2. **Create new app**: `sails new my-app`
305
3. **Navigate to app**: `cd my-app`
306
4. **Lift the app**: `sails lift`
307
5. **Visit**: `http://localhost:1337`
308
309
For detailed API documentation, configuration options, and advanced usage patterns, refer to the comprehensive sub-documentation linked above.