Chapter 2. First steps

This chapter covers

  • Installing the necessary components of the technical stack
  • Setting up the tools of your development environment
  • Creating your first application
  • Cloning your first repository

To get things started, you’ll set up your development environment. This will consist of installing the necessary tools and underlying software to build Sails applications. You’ll then generate a Sails app to apply what you learned in chapter 1. This chapter will also provide an opportunity to demystify the process of backend app creation and dismiss the idea that it has to be a long, drawn-out process. The first application you’ll generate will be disposable. Yep, we said it—disposable. But that’s not a bad thing. It’s actually a feature. Sails is all about rapid development—the ability to have an idea or concept, act on it immediately, create the app, and explore your idea. The bottom line is this: don’t be afraid to experiment. Nothing is wasted. Just relax, explore, and have some fun!

2.1. Tools of the trade

Fortunately, developing modern web backend applications doesn’t require a lot of tools. In fact, you just need a few:

  • Node.js
  • Sails.js
  • A text editor/integrated development environment (IDE)
  • A command-line terminal (shell)

Once these are installed, the underlying applications require very little in the way of configuration. So let’s get busy.

2.1.1. Mac, Windows, and Linux ... oh my!

The decision to develop your application on a particular operating system is a matter of personal choice. We use OS X El Capitan on a MacBook. Most of the examples will be in this context, but if you’re a Windows or Linux shop, they’ll work just as well.

2.1.2. Choosing a text editor vs. an IDE

A text editor is a program that allows you to create and edit files that are stored as plain text. A traditional word processor like Word or Google Docs adds special formatting characters that aren’t displayed but are stored when the file is saved. These special characters can interfere with the computer’s ability to interpret your source code. Therefore, it’s important that any text editor you decide to use stores its files as plain text.

Like your choice of operating system, the choice of a text editor and/or IDE depends on your coding style. We use Sublime Text, but there are many options:

  • Text editors— Sublime Text, TextMate, Notepad++, Vim, Atom, Emacs
  • IDEs— WebStorm, Komodo IDE, Visual Studio, Aptana Studio, Koding (cloud-based)

What’s the difference between a text editor and an IDE? Traditionally, an IDE will have additional tools to automate your coding process like code completion, integration with version control, and added debugging. Over the last several years, the lines between a text editor and an IDE have blurred.

Bottom line

If you’re not already hooked on a particular editor, start with Sublime Text (there’s a free trial) and then experiment with other choices until you find something that best fits your coding style.

2.1.3. Must-have tools

In the OS X world, ShiftIt has become an essential part of the development workflow. Through the use of hotkeys, you can control the placement of windows in your text editor, browser, or any other application. For example, suppose you want to compare two different files in different projects in Sublime Text. You can quickly use the hot-key Ctrl-Option-⌘-↑ to position the first window in the upper half of the screen and Ctrl-Option-⌘-↓ to position the other window in the lower half of the screen. Now these files are positioned so you can easily compare the code. See figure 2.1.

Figure 2.1. Comparing the code of two different projects in Sublime Text with ShiftIt

You’ll constantly move around code windows and browser windows during development, and having ShiftIt makes this process a breeze. You can find ShiftIt at https://github.com/fikovnik/ShiftIt/releases.

Another indispensible tool we use on a daily basis is Postman. Postman makes it super easy to test your backend endpoints via a simple user interface. In addition, Postman allows you to group often-used requests into collections that can be accessed at any time. Collections are not just stored but also synced in realtime. If you work on multiple machines, you can use your Postman account to keep them in sync. Having an account allows you to manage collection links. You can upload collections and get a link that you can give out to others. Postman comes in two versions—a Chrome extension and an OS X installed application. We use the installed application version in the examples in this book. The Chrome extension mirrors all the features that we use in this book with the installed version. To install Postman, navigate your browser to https://www.getpostman.com/apps. You’ll use Postman later in this chapter.

2.1.4. Whoa, command line? Terminal? W-what?

For those not familiar with the command-line terminal (commonly referred to as the Unix shell), this next section is for you. The terminal is a magical place where you can issue commands to your machine without the clutter of a graphical user interface. As a developer, you spend a large portion of your life at the terminal. I realize that may sound depressing, but you’ll soon discover how productive you can be with this essential tool and wonder how you existed without it.

Where’s the terminal?

On a Mac (OS X v10.11.2) you can find the terminal in Applications/Utilities/Terminal.app. When you first launch the terminal, you’ll see something like what’s shown in figure 2.2.

Figure 2.2. The terminal consists of one or more windows or tabs. Each window or tab contains a command line, where you type commands.

In figure 2.2, the terminal is the application you launched. You can open multiple windows or tabs from the terminal, which gives you access to the command line , where you issue commands. Note that your command-line prompt will likely look different from what’s pictured in figure 2.2.

2.1.5. Installing Node

The best way to install Node for OS X or Windows is to use one of the installers shown in figure 2.3.

Figure 2.3. The Node installation page for Windows, OS X, and Linux operating systems

If you’re partial to Linux or SunOS, you can find the binaries for those operating systems as well. Once the installation is complete, open a terminal window and type

~ $ node –v

This command will serve two purposes: verify that Node is installed, as well as provide the version of Node. Now you’re ready to install Sails.

2.1.6. Installing Sails

You’ll use the Node package manager (npm) to install the Sails framework. The Node package manager is included when you install Node and is a way for developers to share and reuse code. Node applications are made up of these packages (or modules) that are stored in various JavaScript files. You can set up a list of files, called dependencies, that you rely on for a given module in a file named package.json. The list of dependencies in package.json will be used by npm to install the necessary files and folders. We’ll explore npm in more detail in the next section. Go back to the terminal window and install Sails from the command-line by typing

~ $ npm install sails –global
Using sudo

You may have to use sudo npm install sails –g, where sudo refers to super user. The user you normally log in as might not have the rights necessary to install something into a root folder. Using sudo allows you to temporarily take on super user rights during installation. In Windows, you may have to open the command prompt as a system administrator.

The –g flag means that npm will install Sails globally, allowing you to generate Sails projects from anywhere in your file system.

At this point, the many files that make up Sails are downloaded and installed on your machine. With one simple command, npm install Sails –g, the package manager determines all the necessary files to install Sails, finds them on the npm registry (npmjs.org), and installs them on your device.

2.2. How code is organized in Node.js

It’s difficult to start a discussion about Node modules, packages, dependencies, and npm because all the concepts are dependent on one another. The Node package manager makes it easy to aggregate, share, and reuse existing JavaScript. npm enables you to aggregate JavaScript into modules, which expose functions and properties you can easily install and use in your project. In fact, Sails is an npm package. Hundreds of thousands of packages are warehoused on registries like www.npmjs.com and available for inclusion in your apps. Even better, once you install a package into your project, npm makes it easy to check for updates and install any dependencies that have changed. npm consists of the three different technologies depicted in figure 2.4.

Figure 2.4. npm consists of a registry with hundreds of thousands of packages , a command-line-interface application , and individual packages .

2.2.1. What is a Node module?

A Node module aggregates related JavaScript code into a single unit. Technically, a module is just a file that exports something. A Node.js file that doesn’t export anything is usually called a script. An npm package is a directory of files that you install from npm. But because npm installs packages into a folder named node_modules/, many Node.js developers (including Isaac Schlueter, the creator of npm, and us) have become accustomed to using the terms npm package, npm module, package, and module interchangeably.

Note

In case you couldn’t guess, we’ll use the terms package and module interchangeably too.

Node modules make source code reusable. Instead of taking a chunk of JavaScript and copying it from one project to another, you can put the code into a module and then require that module from another file. For the most part, we’ll be consumers of modules in this book. Still, to really understand this concept, let’s look at a simple module we built. Here’s the source code of our module.

Example 2.1. the-ultimate-question Node module
module.exports = {

  answer: function() {
    return 42;
  },

  question: function() {
    return 'Sorry, Earth was destroyed before I was able to calculate the
     question.';
  }
};

Instead of getting caught up in the details, just know that this file, named index.js, creates a dictionary with two methods, answer and question.

Definition

Remember, our definition of a dictionary refers to the object that’s declared using curly braces—{}. For example, { foo: 'bar' } is a dictionary.

There’s one other file in the module folder named package.json.

Example 2.2. The package.json file of the-ultimate-question module
{
  "name": "the-ultimate-question",
  "version": "1.0.0",
  "description": "A method to determine the meaning of life",
  "main": "index.js",
  "author": {
    "name": "Irl Nathan"
  },

  "license": "MIT"
}

The package.json file contains information about the module such as name, version, author, and licensing. So this awe-inspiring module consists of two files: index.js and package.json. The repository can be found at https://github.com/irlnathan/the-ultimate-question. Publishing a module goes beyond the scope of the book, but all it would take to publish it to the npmjs.org registry is issuing the command npm publish at the root of the module. Now let’s use our module in a Sails project.

2.2.2. Creating your first Sails application

Let’s create your first application in Sails. Head back to the terminal window and from the command line type

~ $ sails new firstApp
info: Created a new Sails app `firstApp`!
Note

In the example in this section, we displayed what you need to type, sails new firstApp, as well as what was returned, info: Created a new Sails app `firstApp`!.

The new command is part of the Sails command-line interface. We’ll introduce other commands like sails generate in the next section. The command sails new generates the file and folder infrastructure of a boilerplate Sails application. Automating repetitive tasks like generating boilerplate code in your development workflow is a core feature of the Sails framework.

Note that earlier you installed the Sails framework globally on your device. Each time you create a new Sails project, Sails installs itself as a dependency of your project; see figure 2.5.

Figure 2.5. The globally installed version of Sails generated a new Sails application and installed itself as a dependency of the new project .

Your new project is completely self-contained and doesn’t rely on you packaging up some other source files in addition to your project folder to deploy it. You can see the Sails dependency by looking at the firstApp package.json file.

Example 2.3. firstApp’s package.json file

What is the impact of a dependency, and how do you use a third party module? Glad you asked. Let’s put the-ultimate-question module to use in your new app.

2.2.3. Using a module from npm

In chapter 1, you learned that a user-agent could make a request that triggers a route that executes a controller action. The controller action can do stuff and then ultimately respond to the requesting user-agent. Most of the book expands on this process of satisfying requests with controller actions.

Now that you have a project, go to the command line, make sure you’re in the root of the project, and type

~ $ cd firstApp
~/firstApp $

Next, install the-ultimate-question module into the firstApp project by typing

~/firstApp $ npm install the-ultimate-question –save
[email protected] node_modules/the-ultimate-question

You can see the module as a dependency by reopening the firstApp/package.json file in Sublime, similar to the following listing.

Example 2.4. firstApp’s package.json with dependency the-ultimate-question module

Tip

By making the module a dependency, you can copy the project without the node_modules folder and later install all the necessary dependencies by using npm install.

Now, generate a controller by typing

~/firstApp $ sails generate controller life?
info: Created a new controller ("life") at api/controllers/LifeController.js!

In Sublime, open firstApp/api/controllers/LifeController.js and add the following code.

Example 2.5. Adding an action to the LifeController

Okay, let’s see all of this in action.

2.2.4. Starting the Sails server

To start the Sails server, head back to the terminal window and type

~/firstApp $ sails lift

Your terminal window should look similar to figure 2.6.

Figure 2.6. The Sails server up and running

The Sails server is now listening for requests. Navigate your browser to localhost:1337: /life/purpose and your browser should look similar to figure 2.7.

Figure 2.7. The JSON response from the purpose action.

You’re also using the Chrome extension JSONView, which adds syntax highlighting. Figure 2.8 provides an overall illustration of what just happened.

Figure 2.8. An overview of the GET request to /life/purpose

To recap, your browser made a GET request to /life/purpose on your behalf, which matched a blueprint route and triggered the purpose action in the LifeController. The purpose action, which is a JavaScript function, gained access to your previously installed the-ultimate-question module by using the require method and assigning the results to a dictionary you imported as Meaning. You then used the Meaning dictionary to execute two methods from the module and responded to the request using the results of the methods formatted as JSON. This flow, in a nutshell, is the foundation of creating a web application backend.

2.2.5. What is localhost:1337?

The hostname localhost is shorthand for accessing your computer’s local network services. Using localhost usually resolves to the address 127.0.0.1, which is a way of bypassing the outside network. What is the number 1337? Think of the hostname, localhost, as the name of a city and a port number, 1337, as a street address. Separate port numbers are a way to differentiate between applications that are trying to access your computer’s resources. So localhost:1337 is a way to access your device and, more importantly, your project, firstApp, at a particular port.

2.2.6. Killing the server

Now that you understand how to lift a Sails server, let’s see how to lower or close it. From the terminal window, press Ctrl-C, and the terminal window then looks similar to figure 2.9.

Figure 2.9. The terminal window responds with the command prompt after you close the Sails server with Ctrl-C.

What would happen if you typed sails lift in two different tabs of the terminal window? Try it and see what happens. Restart Sails in this tab using sails lift. Next, open a new tabbed window by pressing ⌘-T.

Note

-T opens a new terminal window tab, placing your command-line prompt at the root folder of firstApp.

Now start Sails in this new tab using sails lift, and your terminal window should look similar to figure 2.10.

Figure 2.10. Only one node application at a time can be running on a particular port.

What happens is you can’t run more than one Node application on a particular port at the same time, and if you try to do so Sails produces an error.

2.3. Online resources for this book

The bulk of Sails.js in Action teaches concepts through progressively building an application. To prevent the book from becoming a multivolume set, we’ve provided some additional resources online. The central aggregation of links to all resources can be found on the Sails.js in Action hub: http://sailsinaction.github.io/. The hub contains links to the following:

  • Source files for each chapter stored on the popular Git repository-hosting site GitHub.
  • Gists, which are code snippets that correspond to each program listing in the book. For example, the book might list a small portion of the code to add to an existing source file. The gist will provide the entire file, including the added portion for context.
  • Mockup designs for pages of the application.
  • API and endpoint references.

The main hub contains links for each chapter.

2.3.1. Git and GitHub

Git is another technology that we use day in and day out. It’s an indispensable part of our development flow, and, coupled with GitHub, it’s possible to easily collaborate with others on projects. Version control is a way for you to track the state of one or more files over time and then restore a particular version to some prior state at will. Because this book isn’t about version control, we’ll give you enough information to install Git and clone existing repositories of the source code for each chapter of the book.

2.3.2. Installing Git

Like installing Node, the easiest way to install Git is by using one of its installers. The installer for OS X can be found at http://git-scm.com/download/mac. Once it’s installed, you’ll want to configure Git to identify yourself with your comments. From the terminal window type

~ $ git config --global user.name "Humphrey Bogart"
~ $ git config --global user.email [email protected]

For more extensive information about using Git, check out the great guide at https://git-scm.com/docs.

2.3.3. What is a GitHub repo?

GitHub provides a secure backup of a local repository. It also has a powerful social network of developers with tools that make it easy to collaborate on a repository with people around the world. You’ll use GitHub primarily for copying source files and folders that correspond with each chapter of the book.

The Sails.js in Action hub, http://sailsinaction.github.io/, contains links to an overview page for each chapter. Within each chapter is a link to one or more GitHub repositories. Most chapters will have a beginning repo to clone to your local machine and an ending repo that contains all the activities completed for that particular chapter. Why can’t you simply follow the examples in the book? We wanted to provide you with meaningful frontend source code to utilize while learning backend development. If we attempted to explain and provide the source code for the entire frontend, we could have easily added hundreds of pages to the book. Therefore, for most chapters, we provide the fully baked frontend example before starting the chapter and leave backend development to the pages of the book. If we don’t add assets at the beginning of a chapter, you’ll be given the choice of continuing with a project from the previous chapter or cloning a repository that gets you up to date before starting a chapter.

2.3.4. Cloning a repo

Copying a remote repository is known as cloning. By cloning a repository, you can rapidly obtain all the files of a particular project. Give it a try. Open a browser and navigate to https://github.com/mikermcneil/cursors. Your browser should look similar to figure 2.11.

Figure 2.11. A remote GitHub repository with links to all files in the repo as well as a link to clone the repo

This repo contains files and folders of a Sails app that you’ll install and briefly explore. Copy the link, https://github.com/mikermcneil/cursors.git , in figure 2.11. Open the terminal window and cd to a folder where you’d like to place this project. After installing Git, use the following command to clone the remote repository:

~ $ git clone https://github.com/mikermcneil/cursors.git
Cloning into 'cursors'...
remote: Counting objects: 260, done.
remote: Total 260 (delta 0), reused 0 (delta 0), pack-reused 260
Receiving objects: 100% (260/260), 373.27 KiB | 0 bytes/s, done.
Resolving deltas: 100% (92/92), done.
Checking connectivity... done
~ $

Note that the number of files in your count might vary. Next, cd into the cursors folder and type

~/cursors $ npm install

The command npm install will look for the dependencies in the package.json file in the root of the cursors module and install the necessary dependencies. The cursors application is an example of using WebSockets, which we introduced in chapter 1. Start the application by typing

~/cursors $ sails lift

Now open a browser and navigate to localhost:1337. Open another browser window in incognito mode and navigate to localhost:1337. Enter a phony name when prompted for each browser window. Your browsers should look similar to figure 2.12.

Figure 2.12. The cursors Sails project in action

Every time you move the mouse, Sails sends the position of your cursor to the other browser. This simple example demonstrates the power of WebSockets within Sails. Now that you know how to clone a repo, you’re almost ready to start exploring Sails in earnest by building a real-world application.

2.4. Documentation and community support

Sails has a growing community of developers. Some of the more heavily trafficked areas include these:

2.5. Summary

  • The Sails technical stack consists of Node.js, Sails.js, a text editor, and the command-line shell.
  • Start the Sails server via sails lift and close the server with Ctrl-C.
  • Use npm install to install Node modules into a project.
  • Sails applications can incorporate other Node modules by using the require() method.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset