API-driven framework for building realtime apps, using MVC conventions (based on Express and Socket.io)
—
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.
Start the Sails application by loading configuration, initializing hooks, and binding listeners.
sails.lift(configOverride?: Dictionary, done?: Function): SailsParameters:
configOverride (Dictionary, optional) - Configuration overrides to merge with existing configdone (Function, optional) - Node-style callback (err) => {}Returns: Sails - The Sails instance for method chaining
Events: Emits 'lifted' event on successful startup
Example:
const sails = require('sails');
// Basic lift
sails.lift((err) => {
if (err) throw err;
console.log('Sails app lifted on port', sails.config.port);
});
// Lift with configuration overrides
sails.lift({
port: 3000,
environment: 'development',
log: { level: 'verbose' }
}, (err) => {
if (err) throw err;
console.log('App running on port 3000');
});
// Using events instead of callback
sails.on('lifted', () => {
console.log('Sails app is ready to serve requests!');
});
sails.lift();Lift Process:
Shutdown the Sails application by stopping servers, unbinding listeners, and terminating child processes.
sails.lower(options?: {delay?: Number, hardShutdown?: Boolean}, cb?: Function): voidParameters:
options (Dictionary, optional):
delay (Number) - Delay in milliseconds before shutdown (default: 100ms)hardShutdown (Boolean) - Skip graceful shutdown hooks (default: false)cb (Function, optional) - Node-style callback (err) => {}Example:
// Basic shutdown
sails.lower((err) => {
if (err) throw err;
console.log('Sails app has been lowered.');
});
// Shutdown with options
sails.lower({
delay: 500,
hardShutdown: false
}, (err) => {
if (err) throw err;
console.log('Graceful shutdown completed');
});
// Immediate hard shutdown
sails.lower({ hardShutdown: true });Lower Process:
sails._exiting = true flagbeforeShutdown hookLoad the Sails application without starting HTTP servers. This is primarily used internally but can be useful for testing or script environments.
sails.load(configOverride?: Dictionary, cb?: Function): voidParameters:
configOverride (Dictionary, optional) - Configuration overridescb (Function, optional) - Node-style callback (err) => {}Example:
// Load app for testing without HTTP server
sails.load({
log: { level: 'silent' },
hooks: { http: false } // Disable HTTP hook
}, (err) => {
if (err) throw err;
console.log('App loaded without HTTP server');
// Access models, services, etc.
console.log('Available services:', Object.keys(sails.services || {}));
});Load configuration from .sailsrc files, environment variables, and command-line arguments.
sails.getRc(namespace?: String): DictionaryParameters:
namespace (String, optional) - Configuration namespace (default: 'sails')Returns: Dictionary - Merged configuration object
Configuration Sources (in precedence order):
minimistSAILS_ prefix.sailsrc files (current directory upward).sailsrc files (home directory)Example:
// Get default Sails configuration
const config = sails.getRc();
console.log('Port:', config.port);
console.log('Environment:', config.environment);
// Get custom namespace configuration
const customConfig = sails.getRc('myapp');Environment Variable Parsing:
Environment variables with SAILS_ prefix are automatically parsed:
SAILS_PORT=3000 → config.port = 3000SAILS_LOG__LEVEL=verbose → config.log.level = 'verbose'SAILS_MODELS__MIGRATE=drop → config.models.migrate = 'drop'The application lifecycle emits several key events that you can listen for:
// Application successfully lifted
sails.on('lifted', () => {
console.log('App is ready!');
});
// Application shutdown initiated
sails.on('lower', () => {
console.log('App is shutting down...');
});
// Internal ready state (before lifted)
sails.on('ready', () => {
console.log('App components loaded');
});Sails automatically manages child processes spawned during the application lifecycle:
Properties:
sails.childProcesses (Array) - Array of spawned child processesCleanup:
All child processes are automatically terminated during the lower() process to ensure clean shutdown.
These methods are used internally by Sails but may be relevant for advanced use cases:
sails.initialize(cb: Function): voidInternal method for initializing the Sails instance.
sails.runBootstrap(cb: Function): voidExecute the bootstrap function defined in config/bootstrap.js.
sails.exposeGlobals(): voidExpose configured globals (models, services, etc.) to the global scope.
Lifecycle methods provide comprehensive error handling:
sails.lift((err) => {
if (err) {
console.error('Failed to lift Sails app:', err);
// Check specific error types
if (err.code === 'E_PORT_IN_USE') {
console.error('Port already in use');
}
process.exit(1);
}
});Sails automatically handles process signals for graceful shutdown:
// Graceful shutdown on SIGTERM/SIGINT
process.on('SIGTERM', () => sails.lower());
process.on('SIGINT', () => sails.lower());Common patterns for testing with lifecycle methods:
// Test setup
before((done) => {
sails.load({
log: { level: 'silent' },
hooks: { grunt: false }
}, done);
});
// Test teardown
after((done) => {
sails.lower(done);
});
// Individual test
it('should handle requests', (done) => {
sails.request('/api/users')
.expect(200)
.end(done);
});sails.lift({
environment: 'development',
port: 1337,
log: { level: 'verbose' },
models: { migrate: 'alter' },
session: { secret: 'dev-secret' }
});sails.lift({
environment: 'production',
port: process.env.PORT || 80,
log: { level: 'error' },
models: { migrate: 'safe' },
session: {
secret: process.env.SESSION_SECRET,
cookie: { secure: true }
}
});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.
Install with Tessl CLI
npx tessl i tessl/npm-sails