Skip to main content
Engineering LibreTexts

7.1: Creating and Accessing a Server Using Node.js, Sails

  • Page ID
    27573
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    In this section, an HTTP web CRUD server will be created using Node.js with Sails Blueprints. The HTTP server will be used with the Postman application to explain REST interfaces, and the server will be accessed and tested using the Postman application.

    7.1.1 Node.js

    For the purposes of this text, Node.js can be thought of as a server runtime that is used to run JavaScript. In this way, the node command can be thought of like the java command. Just as the java command runs an interpreter to run Java Byte Code (JBC), so the node command runs an interpreter to run JavaScript. Any JavaScript program can be run with Node.js, not just servers, including interfacing to single board computers like the Raspberry Pi or Arduino 41.

    This book will be using Node.js from within Sails, so there will not be a need to ever directly run the node command for the server that will be created.

    To install Node.js, go to the site https://nodejs.org/en/, and select the option for the latest Long- Term-Release (LTR) version. Then follow the instructions for your operating system. When writing this text, Node.js was installed on a Windows computer, and the LTR downloaded a “.msi” file, and the whole installation completed without any problems.

    To verify the installation of node, open a DOS command window and type “node -v”. You should get back a string describing the version of node you have installed.

    7.1.2 npm

    Most modern languages can access tools, frameworks, and other useful libraries of functionality that are built on top of the language. For example, frameworks have been built for most modern languages that standardize and abstract how interface with databases. For each language, there are multiple number of these frameworks, and no single project would use all of them. Because there are so many, and some conflict with each other, these tools are not built into the base language.

    Not having the tools built into the languages leads to the issue of how to make them available to developers. The old method (and the one still used today in Java) is to require the programmer to manage their own environments. But this is difficult, and except for large environments that can afford to have personal dedicated to this effort, unworkable.

    The modern answer to the tools build problem is to create packages that contain all the files and information needed to install the tool or framework. These packages are then managed by a package manager. Most modern languages have a package manger. For example, in C# there is NuGet, in Ruby these is Ruby-Version-Manager (rvm) and bundler, and in Python there is pip and PyPM.

    Node Package Manager (npm) is the Node.js tool used to manage packages. It is installed by default when you install Node.js. It will be used in the next section to install the Sails package.

    To verify the installation of npm, open a DOS command and type “npm -v”. You should get back a string describing the version of npm you have installed.

    7.1.3 Installing Sails

    When implementing a web server application, most programmers choose a framework to start from. These frameworks provide a standard view of the system, as well as many of the tools that make developing a basic implementation of the application. Later we will see just how simple the basic application development can be.

    Web Sever frameworks generally fall into three large categories: Model-View-Controller (MVC), REpresentational State Transfer (REST), and full-stack. Within MVC, there are two types of frameworks, both of which came from Ruby. They are Sinatra-like and Rails-like. Each of these frameworks has many implementations of the basic scheme, and to see the implementations of these frameworks just in Node.js, see http://nodeframework.com/.

    To attempt to explain in detail even one of these frameworks, let alone all of them, is a task for an entire book, so the details of the frameworks, advantages and disadvantages, etcetera will not be covered. This text will choose one framework, Sails, and will simply use it to create persistent storage for out CRUD application.

    Sails is a MVC Rails-like framework designed to allow a standard implementation of a server application. Sails was chosen simply because the author has used Rails in the past, and at the time this book was written, Sails was one of the most downloaded Rails like frameworks.

    To install Sails, npm will be used. At the DOS command prompt, type

    npm install sails -g
    

    This command tells npm to install the package sails, and to make it globally available for all users. When it completes, you can test that sails has been installed by typing “sails -v”. You should get back a string describing the version of Sails you have installed.

    7.1.4 Implementing your Sails application

    Now that Sails has been installed, an application can be written to store the data from the CRUD application on the server. To start, I suggest that a directory named Sails be created in an appropriate place on your computer, and that you create all of your Sails applications in this directory 42.

    Change Directory (cd) to your Sails application directory and type the following command:

    sails new MapData
    

    Choose option 2, an empty sails application. Option 1 provides a complete basic framework, with authentication, user management, and even credit card processing, and will be the normal option you will choose in the future. For this project though, all of this infrastructure just gets in the way of implementing a simple application, and so do not select it.

    Now generate the specific application we need to store our map data. cd to the MapData directory and type the following command:

    Sails generate api MapData
    

    Doing this has actually generated a Sails Blueprint application that can actually be run, but the application does not know what data it needs to deal with. To fix this, edit the file in your MapData directory named api/models/MapData.js, and change the Primitives section so the file is as follows43.

    Program 111 – api/models/MapData.js file
    
    /**
      * MapData.js 
      *
      * @description :: A model definition. Represents a database table/collection/etc.
      * @docs :: https://sailsjs.com/docs/concepts/models-and- orm/models
      */
    
    module.exports = {
        
        attributes: {
    
        //  ╔═╗╦═╗╦╔╦╗╦╔╦╗╦╦  ╦╔═╗╔═╗
        //  ╠═╝╠╦╝║║║║║ ║ ║╚╗╔╝║╣ ╚═╗
        //  ╩  ╩╚═╩╩ ╩╩ ╩ ╩ ╚╝ ╚═╝╚═╝
        title : 'string',
        resize : 'boolean',
        recenter : 'boolean',
        mapType : 'string',
        screenSize : 'string',
        latitude : 'number',
        longitude : 'number',
        
        //  ╔═╗╔╦╗╔╗ ╔═╗╔╦╗╔═╗
        //  ║╣ ║║║╠╩╗║╣  ║║╚═╗
        //  ╚═╝╩ ╩╚═╝╚═╝═╩╝╚═╝
        
        // ╔═╗╔═╗╔═╗╔═╗╔═╗╦╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
        // ╠═╣╚═╗╚═╗║ ║║ ║║╠═╣ ║ ║║ ║║║║╚═╗    
        // ╩ ╩╚═╝╚═╝╚═╝╚═╝╩╩ ╩ ╩ ╩╚═╝╝╚╝╚═╝
    
        },
    };
    sails.config.models.migrate='alter';        
    

    You also need to add the line sails.config.models.migrate='alter' at the end of the file. This allows the data to be kept between starting instances of the server. The other options for the migrate option are drop (drop the data in the server each time sails is started), and safe, which should be used once the program is in production.

    Now you will start the server by typing the following command:

    sails lift

    The server should now start running, and you should get a screen similar to the following.

    Program 112 – display after sails have started correctly
    
    info: Starting app...
    
     info: ·• Auto-migrating... (alter)
     info: Hold tight, this could take a moment.
     info: ✓ Auto-migration complete.
     info:
     info:              .-..-.
     info:
     info:    Sails            <|    .-..-.
     info:    v1.0.2            |\
     info:                     /|.\
     info:                    / || \
     info:                   ,' |' \                    
     info:               .-'.-==|/_--'
     info:               `--'-------'
     info:     __---___--___---___--___---___--___
     info:   ____---___--___---___--___---___--___-__ 
     info:
     info: Server lifted in `C:\Users\Charl\sails\MapCrud`
     info: To shut down Sails, press <CTRL> + C at any time. 
     info: Read more at https://sailsjs.com/support.
      
    debug: -------------------------------------------------------
    debug: :: Sun Aug 19 2018 11:45:10 GMT-0400 (Eastern Daylight Time)
    
    debug: Environment : development
    debug: Port : 1337
    debug: -------------------------------------------------------      
    

    If you have any errors, check to make sure you are in the MapData directory, and that you spelled all the text in your models file correctly.

    Once you have no errors, a CRUD server with create, read, update, and delete capabilities, is up and running on your local computer (named localhost) and on port 1337. This server is ready to be used by the CRUD application. The rest of this chapter will cover accessing the server.


    41 See https://www.w3schools.com/nodejs/nodejs_intro.asp for more information about running programs using Node.js including creating servers, accessing databases, and programming a Raspberry Pi. For information about using Node.js and Arduino, a google search of “node Arduino” will bring up multiple examples.

    42 The site devdactic.com/rapid-development-with-sailsjs/ provides a good resource for implementing a server in Sails.

    43 For more information about models, see https://sailsjs.com/documentation/co...orm/attributes


    This page titled 7.1: Creating and Accessing a Server Using Node.js, Sails is shared under a CC BY license and was authored, remixed, and/or curated by Charles W. Kann III.

    • Was this article helpful?