CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sails

API-driven framework for building realtime apps, using MVC conventions (based on Express and Socket.io)

Pending
Overview
Eval results
Files

application-lifecycle.mddocs/

Application Lifecycle

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.

Core Lifecycle Methods

lift()

Start the Sails application by loading configuration, initializing hooks, and binding listeners.

sails.lift(configOverride?: Dictionary, done?: Function): Sails

Parameters:

  • configOverride (Dictionary, optional) - Configuration overrides to merge with existing config
  • done (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:

  1. Load configuration from various sources
  2. Initialize and configure all hooks
  3. Load modules (models, controllers, services, etc.)
  4. Bind routes and start HTTP server
  5. Run bootstrap function if configured
  6. Emit 'lifted' event

lower()

Shutdown the Sails application by stopping servers, unbinding listeners, and terminating child processes.

sails.lower(options?: {delay?: Number, hardShutdown?: Boolean}, cb?: Function): void

Parameters:

  • 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:

  1. Set sails._exiting = true flag
  2. Run beforeShutdown hook
  3. Stop HTTP server and close connections
  4. Terminate child processes
  5. Clean up resources and unbind listeners
  6. Execute callback

load()

Load 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): void

Parameters:

  • configOverride (Dictionary, optional) - Configuration overrides
  • cb (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 || {}));
});

Configuration Loading

getRc()

Load configuration from .sailsrc files, environment variables, and command-line arguments.

sails.getRc(namespace?: String): Dictionary

Parameters:

  • namespace (String, optional) - Configuration namespace (default: 'sails')

Returns: Dictionary - Merged configuration object

Configuration Sources (in precedence order):

  1. Command-line arguments parsed with minimist
  2. Environment variables with SAILS_ prefix
  3. Local .sailsrc files (current directory upward)
  4. Global .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=3000config.port = 3000
  • SAILS_LOG__LEVEL=verboseconfig.log.level = 'verbose'
  • SAILS_MODELS__MIGRATE=dropconfig.models.migrate = 'drop'

Lifecycle Events

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');
});

Child Process Management

Sails automatically manages child processes spawned during the application lifecycle:

Properties:

  • sails.childProcesses (Array) - Array of spawned child processes

Cleanup: All child processes are automatically terminated during the lower() process to ensure clean shutdown.

Internal Lifecycle Methods

These methods are used internally by Sails but may be relevant for advanced use cases:

initialize()

sails.initialize(cb: Function): void

Internal method for initializing the Sails instance.

runBootstrap()

sails.runBootstrap(cb: Function): void

Execute the bootstrap function defined in config/bootstrap.js.

exposeGlobals()

sails.exposeGlobals(): void

Expose configured globals (models, services, etc.) to the global scope.

Error Handling

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);
  }
});

Process Signals

Sails automatically handles process signals for graceful shutdown:

// Graceful shutdown on SIGTERM/SIGINT
process.on('SIGTERM', () => sails.lower());
process.on('SIGINT', () => sails.lower());

Testing Patterns

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);
});

Configuration Examples

Development Configuration

sails.lift({
  environment: 'development',
  port: 1337,
  log: { level: 'verbose' },
  models: { migrate: 'alter' },
  session: { secret: 'dev-secret' }
});

Production Configuration

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

docs

actions.md

application-lifecycle.md

cli.md

configuration.md

events.md

hooks.md

index.md

routing.md

tile.json