0
# Application Lifecycle
1
2
The Sails.js application lifecycle provides methods for managing the startup, configuration, and shutdown of your application. These methods handle the complex process of loading hooks, binding servers, and coordinating the various components of your Sails app.
3
4
## Core Lifecycle Methods
5
6
### lift()
7
8
Start the Sails application by loading configuration, initializing hooks, and binding listeners.
9
10
```javascript { .api }
11
sails.lift(configOverride?: Dictionary, done?: Function): Sails
12
```
13
14
**Parameters**:
15
- `configOverride` (Dictionary, optional) - Configuration overrides to merge with existing config
16
- `done` (Function, optional) - Node-style callback `(err) => {}`
17
18
**Returns**: `Sails` - The Sails instance for method chaining
19
20
**Events**: Emits `'lifted'` event on successful startup
21
22
**Example**:
23
```javascript
24
const sails = require('sails');
25
26
// Basic lift
27
sails.lift((err) => {
28
if (err) throw err;
29
console.log('Sails app lifted on port', sails.config.port);
30
});
31
32
// Lift with configuration overrides
33
sails.lift({
34
port: 3000,
35
environment: 'development',
36
log: { level: 'verbose' }
37
}, (err) => {
38
if (err) throw err;
39
console.log('App running on port 3000');
40
});
41
42
// Using events instead of callback
43
sails.on('lifted', () => {
44
console.log('Sails app is ready to serve requests!');
45
});
46
47
sails.lift();
48
```
49
50
**Lift Process**:
51
1. Load configuration from various sources
52
2. Initialize and configure all hooks
53
3. Load modules (models, controllers, services, etc.)
54
4. Bind routes and start HTTP server
55
5. Run bootstrap function if configured
56
6. Emit 'lifted' event
57
58
### lower()
59
60
Shutdown the Sails application by stopping servers, unbinding listeners, and terminating child processes.
61
62
```javascript { .api }
63
sails.lower(options?: {delay?: Number, hardShutdown?: Boolean}, cb?: Function): void
64
```
65
66
**Parameters**:
67
- `options` (Dictionary, optional):
68
- `delay` (Number) - Delay in milliseconds before shutdown (default: 100ms)
69
- `hardShutdown` (Boolean) - Skip graceful shutdown hooks (default: false)
70
- `cb` (Function, optional) - Node-style callback `(err) => {}`
71
72
**Example**:
73
```javascript
74
// Basic shutdown
75
sails.lower((err) => {
76
if (err) throw err;
77
console.log('Sails app has been lowered.');
78
});
79
80
// Shutdown with options
81
sails.lower({
82
delay: 500,
83
hardShutdown: false
84
}, (err) => {
85
if (err) throw err;
86
console.log('Graceful shutdown completed');
87
});
88
89
// Immediate hard shutdown
90
sails.lower({ hardShutdown: true });
91
```
92
93
**Lower Process**:
94
1. Set `sails._exiting = true` flag
95
2. Run `beforeShutdown` hook
96
3. Stop HTTP server and close connections
97
4. Terminate child processes
98
5. Clean up resources and unbind listeners
99
6. Execute callback
100
101
### load()
102
103
Load the Sails application without starting HTTP servers. This is primarily used internally but can be useful for testing or script environments.
104
105
```javascript { .api }
106
sails.load(configOverride?: Dictionary, cb?: Function): void
107
```
108
109
**Parameters**:
110
- `configOverride` (Dictionary, optional) - Configuration overrides
111
- `cb` (Function, optional) - Node-style callback `(err) => {}`
112
113
**Example**:
114
```javascript
115
// Load app for testing without HTTP server
116
sails.load({
117
log: { level: 'silent' },
118
hooks: { http: false } // Disable HTTP hook
119
}, (err) => {
120
if (err) throw err;
121
console.log('App loaded without HTTP server');
122
123
// Access models, services, etc.
124
console.log('Available services:', Object.keys(sails.services || {}));
125
});
126
```
127
128
## Configuration Loading
129
130
### getRc()
131
132
Load configuration from .sailsrc files, environment variables, and command-line arguments.
133
134
```javascript { .api }
135
sails.getRc(namespace?: String): Dictionary
136
```
137
138
**Parameters**:
139
- `namespace` (String, optional) - Configuration namespace (default: 'sails')
140
141
**Returns**: `Dictionary` - Merged configuration object
142
143
**Configuration Sources** (in precedence order):
144
1. Command-line arguments parsed with `minimist`
145
2. Environment variables with `SAILS_` prefix
146
3. Local `.sailsrc` files (current directory upward)
147
4. Global `.sailsrc` files (home directory)
148
149
**Example**:
150
```javascript
151
// Get default Sails configuration
152
const config = sails.getRc();
153
console.log('Port:', config.port);
154
console.log('Environment:', config.environment);
155
156
// Get custom namespace configuration
157
const customConfig = sails.getRc('myapp');
158
```
159
160
**Environment Variable Parsing**:
161
Environment variables with `SAILS_` prefix are automatically parsed:
162
- `SAILS_PORT=3000` → `config.port = 3000`
163
- `SAILS_LOG__LEVEL=verbose` → `config.log.level = 'verbose'`
164
- `SAILS_MODELS__MIGRATE=drop` → `config.models.migrate = 'drop'`
165
166
## Lifecycle Events
167
168
The application lifecycle emits several key events that you can listen for:
169
170
```javascript { .api }
171
// Application successfully lifted
172
sails.on('lifted', () => {
173
console.log('App is ready!');
174
});
175
176
// Application shutdown initiated
177
sails.on('lower', () => {
178
console.log('App is shutting down...');
179
});
180
181
// Internal ready state (before lifted)
182
sails.on('ready', () => {
183
console.log('App components loaded');
184
});
185
```
186
187
## Child Process Management
188
189
Sails automatically manages child processes spawned during the application lifecycle:
190
191
**Properties**:
192
- `sails.childProcesses` (Array) - Array of spawned child processes
193
194
**Cleanup**:
195
All child processes are automatically terminated during the `lower()` process to ensure clean shutdown.
196
197
## Internal Lifecycle Methods
198
199
These methods are used internally by Sails but may be relevant for advanced use cases:
200
201
### initialize()
202
```javascript { .api }
203
sails.initialize(cb: Function): void
204
```
205
Internal method for initializing the Sails instance.
206
207
### runBootstrap()
208
```javascript { .api }
209
sails.runBootstrap(cb: Function): void
210
```
211
Execute the bootstrap function defined in `config/bootstrap.js`.
212
213
### exposeGlobals()
214
```javascript { .api }
215
sails.exposeGlobals(): void
216
```
217
Expose configured globals (models, services, etc.) to the global scope.
218
219
## Error Handling
220
221
Lifecycle methods provide comprehensive error handling:
222
223
```javascript
224
sails.lift((err) => {
225
if (err) {
226
console.error('Failed to lift Sails app:', err);
227
228
// Check specific error types
229
if (err.code === 'E_PORT_IN_USE') {
230
console.error('Port already in use');
231
}
232
233
process.exit(1);
234
}
235
});
236
```
237
238
## Process Signals
239
240
Sails automatically handles process signals for graceful shutdown:
241
242
```javascript
243
// Graceful shutdown on SIGTERM/SIGINT
244
process.on('SIGTERM', () => sails.lower());
245
process.on('SIGINT', () => sails.lower());
246
```
247
248
## Testing Patterns
249
250
Common patterns for testing with lifecycle methods:
251
252
```javascript
253
// Test setup
254
before((done) => {
255
sails.load({
256
log: { level: 'silent' },
257
hooks: { grunt: false }
258
}, done);
259
});
260
261
// Test teardown
262
after((done) => {
263
sails.lower(done);
264
});
265
266
// Individual test
267
it('should handle requests', (done) => {
268
sails.request('/api/users')
269
.expect(200)
270
.end(done);
271
});
272
```
273
274
## Configuration Examples
275
276
### Development Configuration
277
```javascript
278
sails.lift({
279
environment: 'development',
280
port: 1337,
281
log: { level: 'verbose' },
282
models: { migrate: 'alter' },
283
session: { secret: 'dev-secret' }
284
});
285
```
286
287
### Production Configuration
288
```javascript
289
sails.lift({
290
environment: 'production',
291
port: process.env.PORT || 80,
292
log: { level: 'error' },
293
models: { migrate: 'safe' },
294
session: {
295
secret: process.env.SESSION_SECRET,
296
cookie: { secure: true }
297
}
298
});
299
```
300
301
The application lifecycle methods provide the foundation for managing Sails applications across development, testing, and production environments, with comprehensive configuration support and graceful error handling.