The lines that the user needs to enter or customize will be in red in this tutorial!
The rest should mostly be copy-and-pastable.
Sails.js makes it easy to build custom, enterprise-grade Node.js apps. It is designed to mimic the MVC pattern of frameworks like Ruby on Rails, but with support for the requirements of modern apps: data-driven APIs with scalable, service-oriented architecture. It's especially good for building chat, realtime dashboards, or multiplayer games.
In other words: Sails.js allows you to easily create apps with Node.js using the Model-View-Controller pattern to organize your code so it is easier to maintain. Sails.js provides various commands to automate the creation of models and controllers, saving you time and allowing you to create the app faster. (Views have to be created manually in the /views directory in the template /views/:controller/:method.ejs). You are able to use various templating languages, however EJS is the default, and it would be safest and easiest to just stick with EJS.
Sails.js also has various "adapters", allowing you to use virtually any database you want to with your app. This gives you the maximum amount of flexibility, differing from other MVC frameworks that insist on you using MongoDB.
All of these and the fact that on deployment, all of your files are concatenated and minified means that you don't have to spend as much time setting the main framework up to build your app on top of, as it is all ready and easy to use.
sudo apt-get install python-software-properties python g++ makeIf you are using Ubuntu 12.10, you will need to do the following as well:
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
To install the latest stable release of sails, you will need to run:
sudo npm install sails -g
The -g
flag ensures that sails is installed globally and can be used as a command-line tool.
You will want to navigate to the directory in which you would like your app to be located, e.g. /var/www
and then run:
sails new project-name
This will add the required files to your project, and create a directory named project-name.
To view your boilerplate app, you will need to change directory into the project directory and then start the server:
cd project-name
then:
sails lift
This will create a server running at 123.456.78.90:1337, and the page may look something like this (They have changed it a few times, so depending on when you are reading this article, it may be different):
Creating a controller is easy, the sails CLI does all the hard stuff for you. e.g. To create a controller called user with the methods "index, show, edit, delete", all you have to do is run the following command:
sails generate controller user index show edit delete
This will create a file in api/controllers
called UserController.js that looks something like this (giving you helpful hints on what the function does, and how it works):
/*--------------------- :: User -> controller ---------------------*/ var UserController = { // To trigger this action locally, visit: 'http://localhost:port/user/index' index: function(req,res) { // This will render the view: /var/www/sails-test/views/user/index.ejs res.view(); }, // To trigger this action locally, visit: 'http://localhost:port/user/show' show: function(req,res) { // This will render the view: /var/www/sails-test/views/user/show.ejs res.view(); }, // To trigger this action locally, visit: 'http://localhost:port/user/edit' edit: function(req,res) { // This will render the view: /var/www/sails-test/views/user/edit.ejs res.view(); }, // To trigger this action locally, visit: 'http://localhost:port/user/delete' delete: function(req,res) { // This will render the view: /var/www/sails-test/views/user/delete.ejs res.view(); }, }; module.exports = UserController;
Creating a model is as easy as creating a controller with Sails.js. You have no database migrations to worry about, Sails.js does all of that for you intelligently. You are able to use the default in-file database, MySQL or many other database types via "adapters" which can be found by searching around, or looking through the creator's GitHub repositories.
When creating a model, you can specify fields to be added to that model by adding them afterwards, in the format of [name]:[type]
.
e.g. To create a model called user with the fields "name, email, password", all you have to do is run the following command:
sails generate model user name:string email:string password:string
This will create a file in api/models
called User.js that looks something like this:
/*--------------------- :: User -> model ---------------------*/ module.exports = { attributes: { // Simple attribute: // name: 'STRING', // Or for more flexibility: // phoneNumber: { // type: 'STRING', // defaultsTo: '555-555-5555' // } name: { type: 'STRING' }, email: { type: 'STRING' }, password: { type: 'STRING' }, } };
You can generate the Controller and Model at the same time, also generating a Blueprint API that allows you to visit /user and view the raw json representation of the data stored.
sails generate user
The Blueprint API saves you time in the short term by creating connections between your model and controller, allowing you to add new records to the database using that route, e.g. going to http://localhost/user/create?name=John+Smith will create a new user with the name of "John Smith" and print out a JSON array of all of the records created in that model, so the previous URL would print out:
{"name":"John Smith","createdAt":"2013-07-10T20:10:01.038Z","updatedAt":"2013-07-10T20:10:01.038Z","id":1}
In practice, you would want to change or add new methods in the controller, however every new Controller has create(), find(), findAll(), update(), and destroy() methods by default. These can be overridden though, to disable them or just customise them.
The data can also be populated by performing a POST request with a JSON string of the data that you want to insert, e.g.
{ name: 'John Smith' }
Routes can be added by opening config/routes.js
. The file is very well documented using comments, so I feel it is only necessary to add an image rather than describe it, if anything.
When you are ready to deploy an app to production, moving it from port 1337 to 80, Sails.js allows you to do this easily.
port: 1337,to
port: 80,
location / { proxy_pass http://127.0.0.1:1337/; proxy_redirect off;(Leave the Port for Sails.js as 1337)proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
ProxyRequests Off(Leave the Port for Sails.js as 1337)<Proxy *> Order deny,allow Allow from all </Proxy>
ProxyPass / http://127.0.0.1:1337 ProxyPassReverse / http://127.0.0.1:1337
environment: 'development',to
environment: 'production',
sudo npm install -g foreverForever is a node.js package that allows your app to run in the background, without you having to keep terminal open all of the time.
forever start /path/to/app.jsto start the background process. You can check that your app is running in the background by typing in forever list. This will list all running node.js processes (each app is run as a process on the server)
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Chapter Setting the Server to Production Mode “3. If there are multiple apps on the server and
if you are running NGINX
: You will need to modify the server block config to proxy the port that your Sails.js app is being run on by adding:…”You should precise: " You need NGINX or APACHE to manage multiple apps. So if you prefer NGINX first install it and read about those 2 articles :
A/ How To Host Multiple Node.js Applications On a Single VPS with nginx, forever, and crontab
B/ How To Set Up Nginx Server Blocks (Virtual Hosts) on Ubuntu 14.04 LTS "
Thank you for this nice article! I got a question related to the section Setting the Server to Production Mode 3.: If I choose to run Sails on a proxy_pass on port 1337 what would be the recommended way to limit access to my Sails API to localhost? I’d like to run multiple apps on my droplet and use Sails as my API that should only be accessible by the apps in my droplet. – Thanks in advance!
I get after typing this in the console:
this error log message: sails@0.11.0 preinstall /usr/local/lib/node_modules/sails node ./lib/preinstall_npmcheck.js
Sails.js Installation: Checking npm-version successful npm WARN deprecated grunt-lib-contrib@0.7.1: DEPRECATED. See readme: https://github.com/gruntjs/grunt-lib-contrib
ws@0.5.0 install /usr/local/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/node_modules/engine.io/node_modules/ws (node-gyp rebuild 2> builderror.log) || (exit 0)
and sails is not installed. Can someone help me?
Assuming no nginx or Apache (will run on default port 1337 or some other port), what’s the typical/common path for a Sails app? Does it matter?
Chapter Setting the Server to Production Mode “When you are ready to deploy an app to production, moving it from port 1337 to 80, Sails.js allows you to do this easily. 1. Open up config/application.js. …”
It looks like that in the last version of Sails.js (0.10.4) this file does not exist anymore. We should look instead in config/env/production.js
Chapter Starting up the Sails.js server On the 1st start up of the Sails.js server I had a Grunt error :
Possible causes were indicated like this one:
*-> Are "grunt" and related grunt task modules installed locally? Run `npm install` if you're not sure.
So (still in your project folder) run the npm install command and all Sails missing modules will install… and fortunately it resolves this nasty Grunt error.
root# npm install
@jan.strelka this is resolved now-- all the git deps are gone. Thanks for sharing the tip! More deployment info here: https://github.com/balderdashy/sails-docs/blob/master/deployment.md
Good article. Just a quick note… GIT is required by Sails. Try run sudo apt-get install git-core before you install Sails. Worked for me on Ubuntu 12.10.
@tom.hromnik: Simply follow this article and instead of running <code>sails new project-name</code> just transfer the files to /var/www/project-name then proceed with the article.
How to transfer files: <a href=“https://www.digitalocean.com/community/articles/how-to-use-filezilla-to-transfer-and-manage-files-securely-on-your-vps”>https://www.digitalocean.com/community/articles/how-to-use-filezilla-to-transfer-and-manage-files-securely-on-your-vps</a>
that’s all nice, but I won’t develop application on VPS… how to get app running from localhost to VPS?