API-driven framework for building realtime apps, using MVC conventions (based on Express and Socket.io)
—
Sails.js provides a comprehensive command-line interface with 16+ commands for application development, testing, and deployment. The CLI is built on Commander.js and offers extensive options and aliases for efficient development workflows.
Create a new Sails application:
sails new [path] [options]Parameters:
path (String, optional) - Directory name for new application (default: current directory)Options:
--no-frontend - Skip frontend dependencies and assets--fast - Skip npm install (install dependencies manually later)Examples:
# Create new app in current directory
sails new
# Create new app in specific directory
sails new my-awesome-app
# Create API-only app without frontend
sails new my-api --no-frontend
# Create app without installing dependencies
sails new my-app --fast
cd my-app
npm installGenerated Structure:
my-app/
├── api/
│ ├── controllers/
│ ├── models/
│ ├── policies/
│ └── services/
├── config/
├── views/
├── assets/
├── package.json
└── app.jsStart the Sails application:
sails lift [options]
sails l [options] # AliasOptions:
--prod - Start in production environment--staging - Start in staging environment--port [port] - Specify port number--silent - Suppress all log output--verbose - Enable verbose logging--silly - Enable maximum logging detailExamples:
# Basic lift
sails lift
# Production mode
sails lift --prod
# Custom port
sails lift --port 3000
# Verbose logging
sails lift --verbose
# Multiple options
sails lift --prod --port 8080 --silentEnvironment Variables:
# Set environment via variable
NODE_ENV=production sails lift
# Set port via variable
PORT=3000 sails liftGenerate code components (controllers, models, actions, etc.):
sails generate [type] [name] [options]Available Generators:
controller - Generate controllermodel - Generate modelaction - Generate standalone actionhelper - Generate helper functionpage - Generate page (controller + view)api - Generate model + controllerExamples:
# Generate controller
sails generate controller User
# Generate model
sails generate model Product name:string price:number
# Generate API (model + controller)
sails generate api Pet name:string breed:string
# Generate standalone action
sails generate action auth/login
# Generate helper
sails generate helper format-date
# Generate page with view
sails generate page dashboardModel Attributes:
# Generate model with attributes and types
sails generate model User \
email:string \
firstName:string \
lastName:string \
age:number \
isActive:boolean \
avatar:stringStart an interactive REPL with application context:
sails console [options]
sails c [options] # AliasOptions:
--dontLift - Don't lift the Sails app (access limited functionality)--silent - Suppress lift messages--verbose - Enable verbose logging--silly - Enable maximum loggingExamples:
# Start console with full app context
sails console
# Start console without lifting app
sails console --dontLift
# Start console with verbose output
sails console --verboseConsole Usage:
// Access models
sails> User.find()
sails> await User.create({email: 'test@example.com', name: 'Test User'})
// Access services
sails> EmailService.sendWelcomeEmail('user@example.com')
// Access configuration
sails> sails.config.datastores
sails> sails.config.environment
// Run helpers
sails> await sails.helpers.formatDate(new Date())
// Make virtual requests
sails> sails.request('/api/users')Start Sails with Node.js debugger (Node v5 and below):
sails debug [options]Options:
sails liftExample:
# Start with debugger
sails debug
# Debug in production mode
sails debug --prodStart Sails with Node.js inspector (Node v6 and above):
sails inspect [options]Options:
sails liftExamples:
# Start with inspector
sails inspect
# Inspect with custom port
sails inspect --port 3000
# Open Chrome DevTools at chrome://inspectInspector Usage:
sails inspectchrome://inspectRun custom scripts defined in your application:
sails run [script] [options]Parameters:
script (String) - Script name from scripts/ directoryExamples:
# Run custom script
sails run bootstrap-data
# Run with arguments
sails run import-users --file=users.csv
# Run migration script
sails run migrate-databaseScript Structure (scripts/bootstrap-data.js):
module.exports = {
friendlyName: 'Bootstrap data',
description: 'Set up initial application data',
fn: async function(inputs) {
console.log('Bootstrapping initial data...');
// Create admin user
const admin = await User.create({
email: 'admin@example.com',
role: 'admin'
}).fetch();
console.log('Admin user created:', admin.id);
// Create sample data
await Product.createEach([
{ name: 'Product 1', price: 29.99 },
{ name: 'Product 2', price: 39.99 }
]);
console.log('Bootstrap complete!');
}
};Run test suite (alias for sails run test):
sails test [options]Example:
# Run all tests
sails test
# Run specific test file
sails test --grep "User model"Test Configuration (scripts/test.js):
module.exports = {
fn: async function() {
const { execSync } = require('child_process');
try {
// Run Mocha tests
execSync('npm test', { stdio: 'inherit' });
console.log('All tests passed!');
} catch (err) {
console.error('Tests failed:', err.message);
process.exit(1);
}
}
};Run code linting (alias for sails run lint):
sails lint [options]Example:
# Run linting
sails lint
# Fix auto-fixable issues
sails run lint --fixCompile assets to standalone www folder:
sails www [options]Purpose: Generate static website from Sails app for CDN deployment
Example:
# Compile assets
sails www
# Output location: www/
# Contains: Static HTML, CSS, JS, imagesUpgrade Sails application to newer version:
sails upgrade [options]Features:
Example:
# Upgrade to latest Sails version
sails upgrade
# Check what would be upgraded (dry run)
sails upgrade --dry-runRun database migrations:
sails migrate [options]Examples:
# Run pending migrations
sails migrate
# Create new migration
sails migrate create add-user-avatar
# Rollback last migration
sails migrate rollbackDeploy application to cloud platforms:
sails deploy [target] [options]Supported Targets:
heroku - Deploy to Herokuazure - Deploy to Azureaws - Deploy to AWSExamples:
# Deploy to Heroku
sails deploy heroku
# Deploy to specific environment
sails deploy heroku --environment stagingStart debug console session:
sails debug-console [options]
sails dc [options] # AliasPurpose: Interactive debugging with inspector support
Example:
# Start debug console
sails debug-console
# Access in Chrome DevTools
# Set breakpoints in console codeDisplay version information:
sails version
sails --version
sails -v
sails -VOutput Example:
Sails v1.5.15
Node v18.17.0
NPM v9.6.7Display help information:
sails help [command]
sails --helpExamples:
# General help
sails help
# Command-specific help
sails help lift
sails help generate
sails help newMost commands support these global options:
--silent # Suppress log output
--verbose # Enable verbose logging
--silly # Maximum logging detail
--prod # Production environment
--staging # Staging environment
--port [n] # Specify port numberCustomize CLI behavior with .sailsrc file:
{
"generators": {
"modules": {
"controller": "sails-generate-controller-api",
"model": "sails-generate-model-mongoose"
}
},
"commands": {
"lift": {
"environment": "development"
},
"generate": {
"templatesDirectory": "./custom-templates"
}
}
}Create custom code generators:
// generators/my-generator/index.js
module.exports = {
templatesDirectory: require('path').resolve(__dirname, './templates'),
targets: {
'./api/controllers/:filename': { template: 'controller.template' },
'./api/models/:filename': { template: 'model.template' }
},
before: function(scope, cb) {
scope.filename = scope.args[0] + 'Controller.js';
return cb();
}
};Usage:
sails generate my-generator User#!/bin/bash
# deploy.sh
echo "Deploying application..."
# Run tests first
sails test
if [ $? -ne 0 ]; then
echo "Tests failed, aborting deployment"
exit 1
fi
# Build assets
sails www
# Deploy to production
sails deploy heroku --prod
echo "Deployment complete!"{
"scripts": {
"start": "sails lift",
"dev": "sails lift --verbose",
"test": "sails test",
"lint": "sails lint",
"build": "sails www",
"deploy": "./scripts/deploy.sh"
}
}# Development
npm run dev
# Production
NODE_ENV=production npm start
# Testing
npm test
# Building
npm run buildThe Sails.js CLI provides a comprehensive toolkit for efficient application development, testing, and deployment, with extensive customization options and integration capabilities for modern development workflows.
Install with Tessl CLI
npx tessl i tessl/npm-sails