node package manager

11 results back to index


pages: 180 words: 37,187

AngularJS Essentials by Rodrigo Branas

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Firefox, MVC pattern, node package manager, single page application, web application

^ parameter 45 A AngularJS about 7 architectural concepts 9 built-in services 76 data handling 53 history 8 service, creating 69 URL 12, 120 AngularJS $compile documentation URL 47 AngularJS animation about 48 ngClass directive, animating 50 ngHide directive, animating 50 ngRepeat directive, animating 49 working 48 AngularJS built-in directives ngApp directive 19, 20 ngBind directive 21 ngBindHtml directive 22 ngClass directive 27 ngClick directive 25, 26 ngController directive 20 ngDisable directive 26 ngHide directive 31 ngIf directive 31 ngInclude directive 31 ngModel directive 24 ngOptions directive 28-30 ngRepeat directive 22, 23 ngShow directive 30 ngStyle directive 30 other directives 26 using 19 AngularJS built-in services $timeout service 96 asynchronous implementation 98 backend communication 76 logging strategy 96 AngularJS components $httpBackend service, mocking with 132-139 controller 126 directives 129 filters 128 service 125 testing 124 test, running with Karma 140 application organization refactoring 32 architectural concepts, AngularJS controller 9 framework, setting up 10, 11 model 9 view 9 array, orderBy filter 59 Asynchronous JavaScript and XML (AJAX) 79, 80 autoWatch property 142 B backend communication about 76 AJAX 79 caching mechanism 85 headers 84 HTTP 76 HTTP facade, creating 82 interceptors 85, 86 JSON 76, 77 REST method 77 best practices, scope object 106 bootstrapping process 18 Bower about 156 cache 158 installation 156 packages, managing with 156 used, for installing packages 157 used, for searching packages 156 bower.json file 157 C cache, Bower 158 caching mechanism 85 callback 98 code organization about 12, 13 ways 13 code organization, ways domain style 15 inline style 13 specific style 14 stereotyped style 13, 14 cohesion 67 Common Gateway Interface (CGI) 7 compile function used, for creating directive 47 configuration, Grunt 146 constants 74 Content Delivery Network (CDN) URL 12 controller, AngularJS components testing 126 controller function used, for creating directive 46 coupling 68 currency filter 56 D date filter 56 deferred API about 100 notify(value) function 100 reject(reason) function 100 resolve(result) function 100 dependency injection 68, 69 directive 18, 19 directive configuration compile function, using 47 controller function, using 46 link function, using 43 replace property, using 36 require property, using 44-46 restrict property, using 37, 38 scope property, using 38-41 template property, using 35 templateUrl property, using 36 transclude property, using 42 Directive Definition Object 34 directives, AngularJS components compiling 130 creating 18, 34 digest cycle, invoking 130 element, creating 130 [ 160 ] link function, calling with scope 130 testing 129 directive scope configuring 38 distribution package creating, for performance improvement 147 creating, for quality improvement 147 creating, for security improvement 147 grunt-connect plugin, installing 153-155 grunt-contrib-clean plugin, installing 147, 148 grunt-contrib-concat plugin, installing 149 grunt-contrib-copy plugin, installing 150 grunt-contrib-jshint plugin, installing 148 grunt-contrib-uglify plugin, installing 149 grunt-karma plugin, installing 151 Document Object Model (DOM) 17 domain style 15 E expression about 53, 54 interpolation 53 F factory function about 70 used, for creating services 70-73 filters about 55 creating 61 interacting, with expression 55 testing 128 using, in other components 60 filter usage, with expression about 56, 57 currency filter, using 55, 56 date filter, using 56 json format, using 57 limitTo filter, using 58 lowercase filter, using 58 number filter, using 58 orderBy filter, using 59, 60 uppercase filter, using 60 form validation $dirty object 65 $error object 65 $pristine object 65 about 62 basic validation, adding 63, 64 first form, creating 62 framework, AngularJS setting up 10-12 function, orderBy filter 59 G GET method 76 Git repository 156, 157 Google Web Toolkit (GWT) 8 Grunt configuration 146 distribution package, creating 147 installing 146 workflow, automating with 145 workflow, executing 155 grunt-connect plugin installing 153-155 grunt-contrib-clean plugin installing 147, 148 grunt-contrib-concat plugin installing 149 grunt-contrib-copy plugin installing 150 grunt-contrib-jshint plugin installing 148 grunt-contrib-uglify plugin installing 149 Gruntfile.js file 146 grunt-karma plugin installing 151 H headers, backend communication 84, 85 HyperText Markup Language (HTML) 7 HyperText Transfer Protocol (HTTP) 7 I Immediately-Invoked Function Expression (IIFE) 71 inline style 13 installation, Bower 156 [ 161 ] installation, Grunt 146 installation, grunt-connect plugin 153-155 installation, grunt-contrib-clean plugin 147, 148 installation, grunt-contrib-concat plugin 149 installation, grunt-contrib-copy plugin 150 installation, grunt-contrib-uglify plugin 149 installation, grunt-karma plugin 151 installation, packages Bower used 157 interceptors httpTimestampInterceptor 85 httpUnauthorizedInterceptor parameter 86 request interceptor 85 response interceptor 86 J Jasmine 121 Jasmine testing framework about 122-124 URL 122 JavaScript Object Notation (JSON) 57, 77 jQuery library URL 104 JSHint 121, 147 JSLint 121, 147 K Karma about 140 configuring 141 configuring, browser options 141 installing, prerequisites 140 tests, running with 140-142 L limitTo filter 58 link function attrs 43 calling, with scope 130 ctrl 43 element 43 scope 43 transcludeFn 43 used, for creating directive 43 logging strategy levels 96 low cohesion application 67 lowercase filter 58 M Mocha, Karma 141 Model-View-Controller (MVC) pattern 9 Model-View-Whatever (MVW) 9 modules creating 115 parking application 115, 119, 120 search 115, 118, 119 UI 115-118 N nested controllers, ngController directive 21 new operator 74 ngApp directive 19, 20 ngBind directive 21 ngBindHtml directive 22 ngClass directive about 27 animating 50 ngClick directive 25, 26 ngController directive about 20 nested controllers 21 ngDisable directive 26 ngHide directive about 31 animating 50 ngIf directive 31 ngInclude directive 31 ngModel directive 24 ngOptions directive 28-30 ngRepeat directive about 22, 23 animating 49 ngShow directive 30 ngStyle directive 30 NodeJS 146 Node Package Manager (npm) 141, 146 number filter 58 [ 162 ] O one-way data binding mechanism 103 orderBy filter about 59, 60 array 59 function 59 string property 59 P package.jsonfile file 146, 154, 155 packages installing, with Bower 157 managing, with Bower 156 searching, with Bower 156 using 157 parking application module 115, 119, 120 Plain-Old-JavaScript-Object (POJO) 9 POST method 77 prerequisites, Karma installation NodeJS 140 Node Package Manager(npm) 141 promise API catch(errorCallback) 101 finally(callback) 101 then (successCallback, errorCallback, notifyCallback) 101 provider used, for creating services 75, 76 Q QUnit, Karma 141 R recommended modules, AngularJS 120 replace property used, for creating directive 36 Representational State Transfer (REST method) 77 RequireJS, Karma 141 require property used, for creating directive 44-46 restrict property used, for creating directive 37, 38 Revealing Module Pattern 70, 72, 122 RSpec 122 run function 112 S scope object about 103 best practices 106-110 broadcasting 111, 112 scope property used, for creating directive 38-41 search module 115, 118, 119 services, AngularJS components creating 69 creating, with AngularJS service 74 creating, with factory function 70-73 creating, with provider 75, 76 testing 125 single-page application.

You would be interested and also excited to know that Karma was created by Vojta Jína, member of the AngularJS development team at Google. The tool is the result of his Master's thesis called JavaScript Test Runner, for the Czech Technical University in Prague. Installation Before installing Karma, you need to have the NodeJS already installed. It is a quite simple process, and you just need to visit their website, download the package, and proceed with installation. [ 140 ] Chapter 7 After this, you can use the Node Package Manager, also known as npm. It will manage the installation of everything that we need to set up our environment, as follows: npm install –g karma Configuration The configuration is quite simple. It just requires a file called karma.conf.js, located in the root application directory. The best way to create it is by following the configuration wizard through the following command: karma init Karma's configurator will be shown, and you just have to follow the instructions in order to generate your configuration file.

Also, it can group the desired tasks in any sequence, thus creating a workflow. It works over plugins, and there is a huge ecosystem with thousands of choices just waiting to be downloaded! We also have the opportunity to create our own plugins and share them within the community. The warranty is that all of the required tasks of our workflow will be fulfilled! Automating the Workflow Installation Just like Karma, Grunt requires NodeJS and the Node Package Manager to be installed. To proceed with the installation, we just need to type in the following command: npm install -g grunt-cli grunt After this, we are ready to configure it! Configuration The Gruntfile.js file is the JavaScript file that defines the configuration of each task, plugin, and workflow. Let's take a look at its basic structure: module.exports = function (grunt) { // 1 – Configuring each task grunt.initConfig({ }); // 2 - Loading the plug-ins grunt.loadNpmTasks('plugin name'); // 3 - Creating a workflow by grouping tasks together grunt.registerTask('taskName', ['task1','task2','task3']); } Also, it's really recommended that you generate the package.jsonfile file.

 

Learning Node.js: A Hands-On Guide to Building Web Applications in JavaScript by Marc Wandschneider

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

database schema, en.wikipedia.org, Firefox, Google Chrome, node package manager, telemarketer, web application

This approach feels nice and OOP-y, but has the disadvantage of not letting you expose much 91 92 Chapter 5 Modules else from your module; it also tends to feel a bit awkward in the Node way of doing things. I showed it to you here so that you can recognize it for what it is when you see it, but you will almost never use it in this book or your projects—you will largely stick with the factory model. npm: The Node Package Manager Apart from writing your own modules and using those provided by Node.js, you will frequently use code written by other people in the Node community and published on the Internet. The most common way this is done today is by using npm, the Node Package Manager. npm is installed with your node installation (as you saw in Chapter 1, “Getting Started”), and you can go to the command line and type npm help to verify that it’s still there and working. To install modules via npm, you use the npm install command. This technique requires only the name of the module package you want to install.

Maintaining a Sense of Identity 56 Being Polite—Learning to Give Up Control 58 Synchronous Function Calls 61 Summary 61 Part II: Learning to Run 63 4 Writing Simple Applications 65 Your First JSON Server 65 Returning Some Data 67 Node Pattern: Asynchronous Loops 69 Learning to Juggle: Handling More Requests 72 More on the Request and Response Objects 78 Increased Flexibility: GET Params 79 Modifying Things: POST Data 83 Receiving JSON POST Data 84 Receiving Form POST Data 87 Summary 88 Contents 5 Modules 89 Writing Simple Modules 89 Modules and Objects 91 npm: The Node Package Manager 92 Consuming Modules 93 Searching for Modules 93 Module Caching 94 Cycles 95 Writing Modules 95 Creating Your Module 96 Developing with Your Module 101 Publishing Your Modules 102 A Module So Common It Should Be Built In 103 The Problem 104 The Solution 105 Summary 112 6 Expanding Your Web Server 113 Serving Static Content with Streams 113 Reading a File 114 Serving Static Files in a Web Server with Buffers 116 Serving Up More Than Just HTML 118 Assembling Content on the Client: Templates 120 The HTML Skeleton Page 123 Serving Static Content 124 Modifying Your URL Scheme 124 The JavaScript Loader/Bootstrapper 126 Templating with Mustache 127 Your Home Page Mustache Template 129 Putting It All Together 130 Summary 133 Part III Writing Web Applications 135 7 Building Web Applications with Express 137 Installing Express 137 Hello World in Express 138 ix x Contents Routing and Layers in Express 139 Routing Basics 140 Updating Your Photo Album App for Routing 141 REST API Design and Modules 144 API Design 144 Modules 146 Additional Middleware Functionality 148 Usage 148 Configurations 149 Ordering of Middleware 150 Static File Handling 151 POST Data, Cookies, and Sessions 153 Better Browser Support for PUT and DELETE 155 Compressing Output 156 HTTP Basic Authentication 157 Error Handling 158 Summary 159 8 Databases I: NoSQL (MongoDB) 161 Setting Up MongoDB 161 Installing MongoDB 161 Using Mongo DB in Node.js 162 Structuring Your Data for MongoDB 163 It’s All JavaScript 163 Data Types 164 Understanding the Basic Operations 164 Connecting and Creating a Database 165 Creating Collections 165 Inserting Documents into Collections 166 Updating Document Values 167 Deleting Documents from Collections 168 Querying Collections 168 Updating Your Photo Albums App 171 Writing the Low-Level Operations 171 Modifying the API for the JSON Server 177 Updating Your Handlers 177 Adding Some New Pages to the Application 183 Contents Recapping the App Structure 187 Summary 188 9 Databases II: SQL (MySQL) 189 Getting Ready 189 Installing MySQL 189 Adding the mysql Module from npm 190 Creating a Schema for the Database 190 Basic Database Operations 191 Connecting 191 Adding Queries 192 Adding Authentication to the Application Updating the API to Support Users 192 193 Examining the Core User Data Operations Updating the Express Application Creating the User Handler 197 198 Creating the Login and Register Pages Resource Pooling Getting Started 201 204 204 Working with Connections Authenticating the API Summary 193 205 205 209 Part IV Getting the Most Out of Node.js 211 10 Deployment and Development 213 Deployment 213 Level: Basic 214 Level: Ninja 216 Multiprocessor Deployment: Using a Proxy 218 Multiple Servers and Sessions 221 Virtual Hosting 224 Built-in Support 225 Proxy Server Support 227 Securing Your Projects with HTTPS/SSL 227 Generating Test Certificates 228 Built-in Support 228 Proxy Server Support 229 xi xii Contents Multiplatform Development 230 Locations and Configuration Files 230 Handling Path Differences 231 Summary 232 11 Command-Line Programming 233 Running Command-Line Scripts 233 UNIX and Mac 233 Windows 235 Scripts and Parameters 236 Working with Files Synchronously 237 Basic File APIs 237 Files and Stats 239 Listing Contents of Directories 240 Interacting with the User: stdin/stdout 240 Basic Buffered Input-Output 240 Unbuffered Input 241 The Readline Module 243 Working with Processes 247 Simple Process Creation 247 Advanced Process Creation with Spawn 248 Summary 12 Testing 251 253 Choosing a Framework 253 Installing Nodeunit 254 Writing Tests 254 Simple Functional Tests 255 Testing Asynchronous Functionality 258 RESTful API Testing 258 Testing Secured Resources 261 Summary Index 262 263 Acknowledgments I’d like to thank all the Marks at PHPTR (it’s a common name, it seems) who have helped me make this book and other projects a reality.

In addition to all the already-powerful and functional modules that Node provides for you, there is a huge community further developing modules that you can take advantage of in your programs, and indeed you can even write your own to give something back! One of the cool things about Node is that you don’t really distinguish between modules that you have produced and modules that you consume from external repositories, such as those you see later in this chapter via npm, the Node Package Manager. When you write separate classes and groups of functions in Node, you put them in basically the same format—perhaps with a bit less dressing and documentation—as modules you download from the Internet and use. In fact, it usually takes only an extra bit of JSON and maybe a line or two of code to prepare your code for consumption by others! Node ships with a large number of built-in modules, all of which are packaged in the node executable on your system.

 

pages: 325 words: 85,599

Professional Node.js: Building Javascript Based Scalable Software by Pedro Teixeira

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

en.wikipedia.org, Firefox, Google Chrome, node package manager, platform as a service, web application, WebSocket

; Name the file hello_world.js. Then run the file by passing the file path as first argument to the Node executable while inside a shell prompt. For example: $ node hello_world.js Hello World! You can quit the CLI by typing Ctrl+D or Ctrl+C. SETTING UP AND USING NODE PACKAGE MANAGER You can only get so far using the language features and the core functions. That’s why most programming platforms have a system in place that allows you to download, install, and manage third-party modules. In Node, you have Node Package Manager (NPM). NPM is three things — a third-party package repository, a way to manage packages installed in your computer, and a standard to define dependencies on other packages. NPM provides a public registry service that contains all the packages that programmers publish in NPM.

CONTENTS Introduction Part I: Introduction and Setup Chapter 1: Installing Node Installing Node on Windows Installing on Mac OS X Installing Node Using the Source Code Setting Up and Using Node Package Manager Summary Chapter 2: Introducing Node Introducing the Event-Driven Programming Style How Node and JavaScript Make Writing Asynchronous Applications Easier Summary Part II: Node Core API Basics Chapter 3: Loading Modules Understanding How Node Loads Modules Exporting a Module Summary Chapter 4: Using Buffers to Manipulate, Encode, and Decode Binary Data Creating a Buffer Getting and Setting Bytes in a Buffer Slicing a Buffer Copying a Buffer Decoding a Buffer Summary Chapter 5: Using the Event Emitter Pattern to Simplify Event Binding Understanding the Standard Callback Pattern Understanding the Event Emitter Pattern Understanding Event Types Using the Event Emitter API Creating an Event Emitter Summary Chapter 6: Scheduling the Execution of Functions Using Timers Using setTimeout to Defer the Execution of a Function Using clearTimeout to Cancel the Execution of a Function Scheduling and Canceling the Repetitive Execution of a Function Using process.nextTick to Defer the Execution of a Function Until the Next Event Loop Iteration Blocking the Event Loop Escaping the Event Loop Using setTimeout Instead of setInterval to Force Serialization Summary Part III: Files, Processes, Streams, and Networking Chapter 7: Querying, Reading From, and Writing to Files Manipulating File Paths Introducing the fs Module Opening a File Reading from a File Summary Chapter 8: Creating and Controlling External Processes Executing External Commands Spawning Child Processes Signaling and Killing Processes Summary Chapter 9: Reading and Writing Streams of Data Using a Readable Stream Using Writable Streams Considering Some Stream Examples Avoiding the Slow Client Problem and Saving Your Server Summary Chapter 10: Building TCP Servers Creating a TCP Server Building a Simple TCP Chat Server Summary Chapter 11: Building HTTP Servers Understanding the http.ServerRequest Object Understanding the http.ServerResponse Object Streaming HTTP Chunked Responses Shutting Down the Server Example 1: Building a Server that Serves Static Files Example 2: Making Use of HTTP Chunked Responses and Timers Summary Chapter 12: Building a TCP Client Connecting to a Server Sending and Receiving Data Ending the Connection Handling Errors Building an Example Command-Line TCP Client Summary Chapter 13: Making HTTP Requests Making GET Requests Using Other HTTP Verbs Pooling Sockets Using http.Agent Using a Third-Party Request Module to Simplify HTTP Requests Summary Chapter 14: Using Datagrams (UDP) Understanding UDP Understanding the Uses of UDP Building a Datagram Server Creating a Simple Datagram Echo Server Building a Datagram Client Creating a Simple Datagram Command-Line Client Understanding and Using Datagram Multicast Summary Chapter 15: Securing Your TCP Server With TLS/SSL Understanding Private and Public Keys Building a TLS Server Building a TLS Client Building Some Examples Summary Chapter 16: Securing Your HTTP Server With HTTPS Building a Secure HTTP Server Creating an HTTPS Client Summary Part IV: Building and Debugging Modules and Applications Chapter 17: Testing Modules and Applications Using a Test Runner Using an Assertion Testing Module Testing Your Asynchronous Module Summary Chapter 18: Debugging Modules and Applications Using console.log Using Node’s Built-in Debugger Using Node Inspector Summary Chapter 19: Controlling the Callback Flow Understanding the Boomerang Effect Avoiding the Boomerang Effect by Declaring Functions Using the async Flow Control Library Summary Part V: Building Web Applications Chapter 20: Building and Using HTTP Middleware Understanding the Connect HTTP Middleware Framework Building Your Own HTTP Middleware Using the HTTP Middleware Bundled in Connect Summary Chapter 21: Making a Web Application Using Express.js Initializing Your Express.js Application Setting Up Middleware in Your Application Routing Requests Summary Chapter 22: Making Universal Real-Time Web Applications Using Socket.io Understanding How WebSockets Work Using Socket.IO to Build WebSocket Applications Summary Part VI: Connecting to Databases Chapter 23: Connecting to MYSQL Using node-mysql Using a Library to Connect to and Communicate with a MySQL Database Adding Data to the Database with Security Concerns in Mind Reading Data Efficiently Summary Chapter 24: Connecting to CouchDB Using Nano Installing Nano Connecting and Creating a Database Storing Documents Creating and Using CouchDB Views Attaching Files to a CouchDB Document Summary Chapter 25: Connecting to MongoDB Using MongooSE Installing Mongoose Understanding How Mongoose Uses Models to Encapsulate Database Access Connecting to MongoDB Defining a Schema Defining a Model Summary Introduction Advertisements Part I Introduction and Setup CHAPTER 1: Installing Node CHAPTER 2: Introducing Node Chapter 1 Installing Node WHAT’S IN THIS CHAPTER?

CONTENTS Introduction Part I: Introduction and Setup Chapter 1: Installing Node Installing Node on Windows Installing on Mac OS X Installing Node Using the Source Code Setting Up and Using Node Package Manager Summary Chapter 2: Introducing Node Introducing the Event-Driven Programming Style How Node and JavaScript Make Writing Asynchronous Applications Easier Summary Part II: Node Core API Basics Chapter 3: Loading Modules Understanding How Node Loads Modules Exporting a Module Summary Chapter 4: Using Buffers to Manipulate, Encode, and Decode Binary Data Creating a Buffer Getting and Setting Bytes in a Buffer Slicing a Buffer Copying a Buffer Decoding a Buffer Summary Chapter 5: Using the Event Emitter Pattern to Simplify Event Binding Understanding the Standard Callback Pattern Understanding the Event Emitter Pattern Understanding Event Types Using the Event Emitter API Creating an Event Emitter Summary Chapter 6: Scheduling the Execution of Functions Using Timers Using setTimeout to Defer the Execution of a Function Using clearTimeout to Cancel the Execution of a Function Scheduling and Canceling the Repetitive Execution of a Function Using process.nextTick to Defer the Execution of a Function Until the Next Event Loop Iteration Blocking the Event Loop Escaping the Event Loop Using setTimeout Instead of setInterval to Force Serialization Summary Part III: Files, Processes, Streams, and Networking Chapter 7: Querying, Reading From, and Writing to Files Manipulating File Paths Introducing the fs Module Opening a File Reading from a File Summary Chapter 8: Creating and Controlling External Processes Executing External Commands Spawning Child Processes Signaling and Killing Processes Summary Chapter 9: Reading and Writing Streams of Data Using a Readable Stream Using Writable Streams Considering Some Stream Examples Avoiding the Slow Client Problem and Saving Your Server Summary Chapter 10: Building TCP Servers Creating a TCP Server Building a Simple TCP Chat Server Summary Chapter 11: Building HTTP Servers Understanding the http.ServerRequest Object Understanding the http.ServerResponse Object Streaming HTTP Chunked Responses Shutting Down the Server Example 1: Building a Server that Serves Static Files Example 2: Making Use of HTTP Chunked Responses and Timers Summary Chapter 12: Building a TCP Client Connecting to a Server Sending and Receiving Data Ending the Connection Handling Errors Building an Example Command-Line TCP Client Summary Chapter 13: Making HTTP Requests Making GET Requests Using Other HTTP Verbs Pooling Sockets Using http.Agent Using a Third-Party Request Module to Simplify HTTP Requests Summary Chapter 14: Using Datagrams (UDP) Understanding UDP Understanding the Uses of UDP Building a Datagram Server Creating a Simple Datagram Echo Server Building a Datagram Client Creating a Simple Datagram Command-Line Client Understanding and Using Datagram Multicast Summary Chapter 15: Securing Your TCP Server With TLS/SSL Understanding Private and Public Keys Building a TLS Server Building a TLS Client Building Some Examples Summary Chapter 16: Securing Your HTTP Server With HTTPS Building a Secure HTTP Server Creating an HTTPS Client Summary Part IV: Building and Debugging Modules and Applications Chapter 17: Testing Modules and Applications Using a Test Runner Using an Assertion Testing Module Testing Your Asynchronous Module Summary Chapter 18: Debugging Modules and Applications Using console.log Using Node’s Built-in Debugger Using Node Inspector Summary Chapter 19: Controlling the Callback Flow Understanding the Boomerang Effect Avoiding the Boomerang Effect by Declaring Functions Using the async Flow Control Library Summary Part V: Building Web Applications Chapter 20: Building and Using HTTP Middleware Understanding the Connect HTTP Middleware Framework Building Your Own HTTP Middleware Using the HTTP Middleware Bundled in Connect Summary Chapter 21: Making a Web Application Using Express.js Initializing Your Express.js Application Setting Up Middleware in Your Application Routing Requests Summary Chapter 22: Making Universal Real-Time Web Applications Using Socket.io Understanding How WebSockets Work Using Socket.IO to Build WebSocket Applications Summary Part VI: Connecting to Databases Chapter 23: Connecting to MYSQL Using node-mysql Using a Library to Connect to and Communicate with a MySQL Database Adding Data to the Database with Security Concerns in Mind Reading Data Efficiently Summary Chapter 24: Connecting to CouchDB Using Nano Installing Nano Connecting and Creating a Database Storing Documents Creating and Using CouchDB Views Attaching Files to a CouchDB Document Summary Chapter 25: Connecting to MongoDB Using MongooSE Installing Mongoose Understanding How Mongoose Uses Models to Encapsulate Database Access Connecting to MongoDB Defining a Schema Defining a Model Summary Introduction Advertisements Part I Introduction and Setup CHAPTER 1: Installing Node CHAPTER 2: Introducing Node Chapter 1 Installing Node WHAT’S IN THIS CHAPTER? Getting Node up and running Installing Node Package Manager (NPM) Using NPM to install, uninstall, and update packages At the European JSConf in 2009, Ryan Dahl, a young programmer, presented a project he had been working on. This project was a platform that combined Google’s V8 JavaScript engine, an event loop, and a low-level I/O API. This project was not like other server-side JavaScript platforms where all the I/O primitives were event-driven and there was no way around it.

 

pages: 290 words: 119,172

Beginning Backbone.js by James Sugrue

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Airbnb, continuous integration, Firefox, Google Chrome, loose coupling, MVC pattern, node package manager, single page application, web application, Y Combinator

At the time of this writing, the unminimizedruntime library was 11KB, while the full Handlebars library was 73KB. When targeting mobile devices, such savings can be significant. You will need Node.js installed on your development or build machine to run precompilation. In Chapter 3, we created a Node.js server to act as a backend to our application. If you haven’t already installed node.js, you can download it from http://nodejs.org. Once you have node.js installed, you can use the node package manager (NPM) to download the handlebars package.   npm install handlebars -g   All templates will need to be stored in an external file, which is passed to the precompiler on the command line.   handlebars<inputfile> -f <outputfile>   This will result in a JavaScript file being created that contains the compiled template, which can then be included within your application. Templating with Mustache Mustache.js is another logic-less templating library, available from http://mustache.github.io.

As well as allowing you to run your tests in headless mode (in other words, without rendering the user interface elements), PhantomJS even has the ability to take screenshots of the browser at any particular time. Installation instructions for PhantomJS are available on the project web site under http://phantomjs.org/download.html, as illustrated in Figure 8-6, where you will be instructed to download the appropriate installer for your operating system. However, if you are already using Node.js, you can use the Node Package Manager to install PhantomJS by using the following command:  npm install phantomjs   162 Chapter 8 ■ Testing Your Backbone.js Application Figure 8-6.  PhantomJS web site at http://phantomjs.org Now that you have PhantomJS installed, you will need to obtain the PhantomJS Runner plug-in for QUnit, runner.js, from https://github.com/jquery/qunit/tree/master/addons/phantomjs. Unlike other scripts, we have downloaded throughout this book, runner.js will be executed from the command line.

Installing Grunt If you want to use Grunt, you will need to install Node.js first. If you’ve been following the examples in this book, you will already have Node.js installed. If you haven’t, go to http://nodejs.org and follow the installation steps for your operating system. 180 Chapter 9 ■ Using Grunt for Your Build Process The Grunt command-line interface (CLI) is installed through the Node Package Manager by executing the following on the command line, using the -g flag to ensure it is installed globally. Note that you will need to execute this with admin rights; on Mac OS X this means prefixing the command with sudo.     npm install -g grunt-cli   To check that it has successfully installed, run grunt --help from the command line. Adding Grunt to Existing Projects Running the grunt command from your terminal will result in an error message stating that the Gruntfile could not be found.

 

pages: 190 words: 52,865

Full Stack Web Development With Backbone.js by Patrick Mulder

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Airbnb, create, read, update, delete, Debian, MVC pattern, node package manager, side project, single page application, web application

Send email to index@oreilly.com. 165 Backbone.Collection, sorting/filtering models with, 61–71 Backbone.js dependencies, 2 distributed application design, 6 fetching local copy of, 4 fetching via content delivery networks, 5 fetching with Node’s package manager, 2 philosophy of, 2, 145 Backbone.Model building a data layer, 26 data resolution, 88 DRYer Views and ViewModels, 46 modal view, 125 sorting, 62 wrapping a data store, 101 Backbone.ModelBinder, 39 Backbone.Obscura, 68, 137 Backbone.Router addressing state, 49–55 orchestrating views, 55–60 overview of, 49 Backbone.Sync, 84, 87 Backbone.View basic events, 31 basic rendering, 37 basic view templates, 41 DRYer Views and ViewModels, 46 filtering, 66 handling UI events, 43 modal view, 125 navbar view, 123 parent/child views, 56 rendering a collection, 42 sorting, 62 templates, 74 Backburner, 76 backend-as-a-service providers, 94, 98 bind function, 159 bindAll function, 159 binding, 39 Bluebird library, 103 Bower, 136 Browserify, 10, 29, 136 browsers development console, 15 DOM representation in, 161 packaging modules for, 9 166 | Index security in, 113 (see also authentication) browsing experience mock-up, 19 Brunch, 136 build automation goals of, 77 Grunt, 77 overview of, 135 scaffolding components, 143 tools to improve productivity, 135 Yeoman, 138 C callbacks, 103 Catero, 136 Cavage, Mark, 100 chaining methods, 161 change events, 28 Chaplin framework, 136, 146 child views, 56 className property, 37 click dummy basic CSS for, 25 basic events, 31 basic HTML for, 24 data layer, 26 preparation overview, 24 Cloudflare, 5 Cocoa API, 22 Codepen.io, 5 CoffeeScript, 136 collection helpers, 161 collections filtering, 21, 66 pagination, 68 sorting, 21, 62 transforming, 61 Underscore.js helpers, 158 command line interface (CLI) benefits of, 1 bundling modules from, 10 npm (Node package manager), 2 CommonJS modules benefits of, 8 Browserify, 10 Cartero management system, 136 Express.js and Stitch, 13 require in browsers, 9 comparator function, 62 content delivery network (CDN), 5 controllers, 24, 55 convention-over-configuration, 147 cookies drawbacks of, 115, 118 overview of, 114 session management, 118 user signup, 116 CORS (cross origin resource sharing), 99 createUser method, 116 cross-site request forgery (CSRF), 114 cross-site scripting (XSS), 114 D data binding, 39 building the data layer, 26 controlling access to, 113 (see also authentication) representation with models, 21 transforming with Underscore.js, 158 databases non-relational, 98 NoSQL, 98 relational, 98 wrapping data stores behind an API, 101 debuggers, 15 Decker, Kevin, 145 default properties, 27 dependencies managing with Bower, 136 resolving with main.js file, 141 reusing across projects, 8 Underscore.js, 158–160 Document Object Model (DOM) changing multiple nodes at once, 76 manipulation libraries, 2 node types, 161 statelessness and, 19 DOM nodes attaching/removing event handlers, 162 chaining methods on, 161 operating on directly, 161 preventing event bubbling, 162 selecting with jQuery, 161 types of, 161 DRYer views, 46 E Eastridge, Ryan, 145 ECO (embedded CoffeeScript), 75 event bubbling, 162 event handlers attaching/removing, 162 for UI events, 43 event listeners, 39 events change events, 28 default, 31 handling UI events, 43 sources of, 21, 31 Express.js, 13, 100 extend function, 27, 160 F fetching information asynchronous effects, 92 from hosted backend services, 94 overview of, 83, 87 RESTful web service handling, 84 filtering, 66 Firebase, 94 frameworks benefits of, 145 Chaplin, 146 Giraffe, 146 Junior, 146 Marionette, 146 Rendr, 146 Thorax.js, 146 Function.prototype.bind, 159 functional programming, 158 functions binding context to, 159 get, 28 private, 28 set, 28 sharing across multiple objects, 160 G get function, 28 Giraffe, 146 Grunt, 77 Index | 167 H Handlebars, 76 hashes/hashbangs, 50 Homebrew package manager, 157 HTTP requests basic verbs, 84 cookies, 115 sending from JavaScript, 163 signing, 114 HTTP responses, 102 I index.html, 9 inheritance, 160 isomorphic application design, 97 J JavaScript adding moudles from command line, 143 Ajax, 163 basic abstractions for Backbone.js, 1 debugging, 15 distributed application design, 6 HTTP requests from, 163 jQuery basics of, 160 element selection, 161 event handling, 162 Node.js installation, 157 overview of, 157 promises, 102 Underscore.js benefits of, 158 collections/arrays, 158 functions, 159 objects, 160 utility functions, 160 (see also objects) jQuery Ajax browsing experience mock-up, 19 jQuery API for, 163 basics of, 160 chaining methods, 161 collection helpers, 161 element selection, 161 event handling, 162 168 | Index node wrappers, 161 referencing, 35 JSBin, 5 JSFiddle, 5 JSLint/JSHint, 16 JST (JavaScript Templates), 74 Junior, 146 K key-value pairs data representation with, 21 primary keys, 107 syntax considerations for, 28 L LAMP (Linux-Apache-MySQL-PHP), 98 Layout View, 55 Linux, Node.js installation, 157 M Mac OS Homebrew package manager, 157 Node.js installation, 157 main.js file, 141 Marionette, 146 Mincer, 13 mixin functions, 46 mock-ups APIs, 85 browsing experience, 19 data, 149 wireframes, 19 Mockjax, 149 modal view, 125 model parameter, 29 model-view-controller (MVC) pattern, 22 models (see Backbone models) modules Browserify, 10 bundling from command line, 10 choosing, 8 CommonJS, 8 packaging for browsers, 9 RequireJS, 142 Morell, Jeremy, 68 Munich Cinema example API creation, 100 click dummy preparation basic CSS, 25 basic events, 31 basic HTML, 24 data layer, 26 overview of, 24 current web page, 18 preliminary mock-up, 19 project goals, 18 star rating/voting system, 108 synchronizing state in basic sync and fetch, 87 fetching remote movies, 84 goals of, 83 user interface DRYer views/ViewModels, 46 goals for, 35 handling UI events, 43 interfacing the DOM, 36–43 referencing jQuery, 35 N Navbar view, 123 navigate function, 54 navigation view (navbar), 123 NeXTSTEP operating system, 22 noBackend providers, 94, 98 Node.js installation of, 157 package manager, 2 read-eval-print-loop (REPL), 15 nodes (see DOM nodes) non-relational data stores, 98 npm (Node package manager), 2, 8 O object-relational-mapper (ORM), 98 objects customizing interfaces of, 160 rendering within templates, 160 open-source software, 4 P package managers, 13 pagination, 68 parent views, 56 passwords, 113 (see also authentication) persistence, 101, 108 primary keys, 107 private functions, 28 productivity, improving, 135 (see also workflow automation) promises, 103 proxies, 98 publish-subscribe pattern, 31 pushState(), 50 R React.js, 77 read-eval-print-loop (REPL), 15, 29 relational databases, 98 render function, 37 Rendr, 146 representations in RESTful web services, 85 with models, 21 RequireJS adding modules, 142 benefits of, 140 main.js file, 141 RESTful web services, 84 Restify library, 100 router basics addressing state defining routes, 51 goal of, 49 navigating, 54 preparing, 50 orchestrating views Layout View, 55 parent/child views, 56 overview of, 49 S security, 113 (see also authentication) session management Backbone applications API calls, 118 login dialog, 129 modal view, 125 navbar view, 123 cookies, 118 Index | 169 creating new, 131 logout, 132 set function, 28 signing requests approaches to, 114 benefits of, 114 sorting, 62 Sprockets, 13 state addressing with routers defining routes, 51 goal of, 49 navigating, 54 preparing, 50 authentication and, 131 decoupling from UI benefits of, 22 models and collections, 21 MVC pattern, 22 need for, 19 views, 22 synchronizing basic sync and fetch, 87 fetching remote information, 84 overview of, 83 statelessness, 19, 84 Stitch, 13 T tagName property, 37 template property, 41, 75 templates embedded CoffeeScript, 75 Handlebars, 76 JavaScript Templates, 74 overview of, 73 Thorax.js benefits of, 145 getting started application initialization, 150 build tasks, 147 installation/setup of, 147 mock data preparation, 149 overview of, 146 rendering advanced views, 154 Router setup, 152 Thorax.Collection, 152 TodoMVC demo, 24 tokens, access, 114 170 | Index U Ubuntu, Node.js installation, 157 Underscore.js benefits of, 158 collections/arrays, 158 functions, 159 objects, 160 utility functions, 160 user interface decoupling from state benefits of, 22 models and collections, 21 MVC pattern, 22 need for, 19 views, 22 DRYer views/ViewModels, 46 goals for, 35 handling UI events, 43 interfacing the DOM basic rendering, 37 basic view templates, 41 bindings to data changes, 39 rendering a collection, 42 strategy overview, 36 referencing jQuery, 35 V ViewModels, 46 views advanced view templates, 73 Backbone views, 22 data display management with, 23 DRYer view/ViewModels, 46 Layout View, 55 modal view, 125 MVC pattern, 22 navbar view, 123 parent/child views, 56 updating immediately, 39 welcome view, 59 vulnerabilities cross-site request forgery (CSRF), 114 cross-site scripting (XSS), 114 W Walmart’s shopping cart, 147 welcome view, 59 Windows, Node.js installation, 157 wireframes benefits of, 19 creating, 18 workflow, automation of (see build automation) X benefits of, 136, 138 installation of, 138 running, 139 Z Zepto library, 2, 160 XMLHttpRequest object, 163 Y Yeoman application directory, 140 Index | 171 About the Author Before discovering software development for web applications with Java and Ruby in 2008, Patrick Mulder mainly worked as a software engineer on measurement equip‐ ment and electronic devices.

Send email to index@oreilly.com. 165 Backbone.Collection, sorting/filtering models with, 61–71 Backbone.js dependencies, 2 distributed application design, 6 fetching local copy of, 4 fetching via content delivery networks, 5 fetching with Node’s package manager, 2 philosophy of, 2, 145 Backbone.Model building a data layer, 26 data resolution, 88 DRYer Views and ViewModels, 46 modal view, 125 sorting, 62 wrapping a data store, 101 Backbone.ModelBinder, 39 Backbone.Obscura, 68, 137 Backbone.Router addressing state, 49–55 orchestrating views, 55–60 overview of, 49 Backbone.Sync, 84, 87 Backbone.View basic events, 31 basic rendering, 37 basic view templates, 41 DRYer Views and ViewModels, 46 filtering, 66 handling UI events, 43 modal view, 125 navbar view, 123 parent/child views, 56 rendering a collection, 42 sorting, 62 templates, 74 Backburner, 76 backend-as-a-service providers, 94, 98 bind function, 159 bindAll function, 159 binding, 39 Bluebird library, 103 Bower, 136 Browserify, 10, 29, 136 browsers development console, 15 DOM representation in, 161 packaging modules for, 9 166 | Index security in, 113 (see also authentication) browsing experience mock-up, 19 Brunch, 136 build automation goals of, 77 Grunt, 77 overview of, 135 scaffolding components, 143 tools to improve productivity, 135 Yeoman, 138 C callbacks, 103 Catero, 136 Cavage, Mark, 100 chaining methods, 161 change events, 28 Chaplin framework, 136, 146 child views, 56 className property, 37 click dummy basic CSS for, 25 basic events, 31 basic HTML for, 24 data layer, 26 preparation overview, 24 Cloudflare, 5 Cocoa API, 22 Codepen.io, 5 CoffeeScript, 136 collection helpers, 161 collections filtering, 21, 66 pagination, 68 sorting, 21, 62 transforming, 61 Underscore.js helpers, 158 command line interface (CLI) benefits of, 1 bundling modules from, 10 npm (Node package manager), 2 CommonJS modules benefits of, 8 Browserify, 10 Cartero management system, 136 Express.js and Stitch, 13 require in browsers, 9 comparator function, 62 content delivery network (CDN), 5 controllers, 24, 55 convention-over-configuration, 147 cookies drawbacks of, 115, 118 overview of, 114 session management, 118 user signup, 116 CORS (cross origin resource sharing), 99 createUser method, 116 cross-site request forgery (CSRF), 114 cross-site scripting (XSS), 114 D data binding, 39 building the data layer, 26 controlling access to, 113 (see also authentication) representation with models, 21 transforming with Underscore.js, 158 databases non-relational, 98 NoSQL, 98 relational, 98 wrapping data stores behind an API, 101 debuggers, 15 Decker, Kevin, 145 default properties, 27 dependencies managing with Bower, 136 resolving with main.js file, 141 reusing across projects, 8 Underscore.js, 158–160 Document Object Model (DOM) changing multiple nodes at once, 76 manipulation libraries, 2 node types, 161 statelessness and, 19 DOM nodes attaching/removing event handlers, 162 chaining methods on, 161 operating on directly, 161 preventing event bubbling, 162 selecting with jQuery, 161 types of, 161 DRYer views, 46 E Eastridge, Ryan, 145 ECO (embedded CoffeeScript), 75 event bubbling, 162 event handlers attaching/removing, 162 for UI events, 43 event listeners, 39 events change events, 28 default, 31 handling UI events, 43 sources of, 21, 31 Express.js, 13, 100 extend function, 27, 160 F fetching information asynchronous effects, 92 from hosted backend services, 94 overview of, 83, 87 RESTful web service handling, 84 filtering, 66 Firebase, 94 frameworks benefits of, 145 Chaplin, 146 Giraffe, 146 Junior, 146 Marionette, 146 Rendr, 146 Thorax.js, 146 Function.prototype.bind, 159 functional programming, 158 functions binding context to, 159 get, 28 private, 28 set, 28 sharing across multiple objects, 160 G get function, 28 Giraffe, 146 Grunt, 77 Index | 167 H Handlebars, 76 hashes/hashbangs, 50 Homebrew package manager, 157 HTTP requests basic verbs, 84 cookies, 115 sending from JavaScript, 163 signing, 114 HTTP responses, 102 I index.html, 9 inheritance, 160 isomorphic application design, 97 J JavaScript adding moudles from command line, 143 Ajax, 163 basic abstractions for Backbone.js, 1 debugging, 15 distributed application design, 6 HTTP requests from, 163 jQuery basics of, 160 element selection, 161 event handling, 162 Node.js installation, 157 overview of, 157 promises, 102 Underscore.js benefits of, 158 collections/arrays, 158 functions, 159 objects, 160 utility functions, 160 (see also objects) jQuery Ajax browsing experience mock-up, 19 jQuery API for, 163 basics of, 160 chaining methods, 161 collection helpers, 161 element selection, 161 event handling, 162 168 | Index node wrappers, 161 referencing, 35 JSBin, 5 JSFiddle, 5 JSLint/JSHint, 16 JST (JavaScript Templates), 74 Junior, 146 K key-value pairs data representation with, 21 primary keys, 107 syntax considerations for, 28 L LAMP (Linux-Apache-MySQL-PHP), 98 Layout View, 55 Linux, Node.js installation, 157 M Mac OS Homebrew package manager, 157 Node.js installation, 157 main.js file, 141 Marionette, 146 Mincer, 13 mixin functions, 46 mock-ups APIs, 85 browsing experience, 19 data, 149 wireframes, 19 Mockjax, 149 modal view, 125 model parameter, 29 model-view-controller (MVC) pattern, 22 models (see Backbone models) modules Browserify, 10 bundling from command line, 10 choosing, 8 CommonJS, 8 packaging for browsers, 9 RequireJS, 142 Morell, Jeremy, 68 Munich Cinema example API creation, 100 click dummy preparation basic CSS, 25 basic events, 31 basic HTML, 24 data layer, 26 overview of, 24 current web page, 18 preliminary mock-up, 19 project goals, 18 star rating/voting system, 108 synchronizing state in basic sync and fetch, 87 fetching remote movies, 84 goals of, 83 user interface DRYer views/ViewModels, 46 goals for, 35 handling UI events, 43 interfacing the DOM, 36–43 referencing jQuery, 35 N Navbar view, 123 navigate function, 54 navigation view (navbar), 123 NeXTSTEP operating system, 22 noBackend providers, 94, 98 Node.js installation of, 157 package manager, 2 read-eval-print-loop (REPL), 15 nodes (see DOM nodes) non-relational data stores, 98 npm (Node package manager), 2, 8 O object-relational-mapper (ORM), 98 objects customizing interfaces of, 160 rendering within templates, 160 open-source software, 4 P package managers, 13 pagination, 68 parent views, 56 passwords, 113 (see also authentication) persistence, 101, 108 primary keys, 107 private functions, 28 productivity, improving, 135 (see also workflow automation) promises, 103 proxies, 98 publish-subscribe pattern, 31 pushState(), 50 R React.js, 77 read-eval-print-loop (REPL), 15, 29 relational databases, 98 render function, 37 Rendr, 146 representations in RESTful web services, 85 with models, 21 RequireJS adding modules, 142 benefits of, 140 main.js file, 141 RESTful web services, 84 Restify library, 100 router basics addressing state defining routes, 51 goal of, 49 navigating, 54 preparing, 50 orchestrating views Layout View, 55 parent/child views, 56 overview of, 49 S security, 113 (see also authentication) session management Backbone applications API calls, 118 login dialog, 129 modal view, 125 navbar view, 123 cookies, 118 Index | 169 creating new, 131 logout, 132 set function, 28 signing requests approaches to, 114 benefits of, 114 sorting, 62 Sprockets, 13 state addressing with routers defining routes, 51 goal of, 49 navigating, 54 preparing, 50 authentication and, 131 decoupling from UI benefits of, 22 models and collections, 21 MVC pattern, 22 need for, 19 views, 22 synchronizing basic sync and fetch, 87 fetching remote information, 84 overview of, 83 statelessness, 19, 84 Stitch, 13 T tagName property, 37 template property, 41, 75 templates embedded CoffeeScript, 75 Handlebars, 76 JavaScript Templates, 74 overview of, 73 Thorax.js benefits of, 145 getting started application initialization, 150 build tasks, 147 installation/setup of, 147 mock data preparation, 149 overview of, 146 rendering advanced views, 154 Router setup, 152 Thorax.Collection, 152 TodoMVC demo, 24 tokens, access, 114 170 | Index U Ubuntu, Node.js installation, 157 Underscore.js benefits of, 158 collections/arrays, 158 functions, 159 objects, 160 utility functions, 160 user interface decoupling from state benefits of, 22 models and collections, 21 MVC pattern, 22 need for, 19 views, 22 DRYer views/ViewModels, 46 goals for, 35 handling UI events, 43 interfacing the DOM basic rendering, 37 basic view templates, 41 bindings to data changes, 39 rendering a collection, 42 strategy overview, 36 referencing jQuery, 35 V ViewModels, 46 views advanced view templates, 73 Backbone views, 22 data display management with, 23 DRYer view/ViewModels, 46 Layout View, 55 modal view, 125 MVC pattern, 22 navbar view, 123 parent/child views, 56 updating immediately, 39 welcome view, 59 vulnerabilities cross-site request forgery (CSRF), 114 cross-site scripting (XSS), 114 W Walmart’s shopping cart, 147 welcome view, 59 Windows, Node.js installation, 157 wireframes benefits of, 19 creating, 18 workflow, automation of (see build automation) X benefits of, 136, 138 installation of, 138 running, 139 Z Zepto library, 2, 160 XMLHttpRequest object, 163 Y Yeoman application directory, 140 Index | 171 About the Author Before discovering software development for web applications with Java and Ruby in 2008, Patrick Mulder mainly worked as a software engineer on measurement equip‐ ment and electronic devices.

 

pages: 59 words: 12,801

The Little Book on CoffeeScript by Alex MacCaw

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Firefox, MVC pattern, node package manager, web application, Y2K

In fact, you can use the browser-based CoffeeScript compiler yourself, by including this script in a page, marking up any CoffeeScript script tags with the correct type: <script src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js" type="text/javascript" charset="utf-8"></script> <script type="text/coffeescript"> # Some CoffeeScript </script> Obviously, in production, you don’t want to be interpreting CoffeeScript at runtime, as it’ll slow things up for your clients. Instead, CoffeeScript offers a Node.js compiler to pre-process CoffeeScript files. To install it, first make sure you have a working copy of the latest stable version of Node.js and npm (the Node Package Manager). You can then install CoffeeScript with npm: npm install -g coffee-script The -g flag is important, as it tells npm to install the coffee-script package globally, rather than locally. Without it, you won’t get the coffee executable. If you execute the coffee executable without any command line options, it’ll give you the CoffeeScript console, which you can use to quickly execute CoffeeScript statements.

 

pages: 323 words: 65,306

Programming in CoffeeScript by Mark Bates

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

en.wikipedia.org, MVC pattern, node package manager, single page application, web application

To do this we are going to use the most popular Node framework out there, Express.2 Express is easy to install and get up and running fairly quickly, and it has a vibrant development community, which makes it a great choice for the task at hand. In a nice, fresh directory, let’s create a new file, app.coffee, that will be the starting point for our Express backend. Right now, let’s just leave that file blank while we install Express. Express ships as an NPM,3 Node Package Manager, module. We briefly mentioned NPM in Chapter 9, “Intro to Node.js.” NPM modules are bundles of code that are packaged up and distributed and can then be installed, included, and required into Node applications. If you have Node installed, you should already have NPM installed. Installing Express is a simple one liner: > npm install express You should see output similar to this: express@2.5.2 .

I really do love it and use it all the time. 5. http://documentcloud.github.com/underscore 6. http://zeptojs.com 7. https://github.com/codebrew/backbone-rails 8. http://www.mongodb.org/ 9. https://github.com/markbates/Programming-In-CoffeeScript 275 This page intentionally left blank Index @ alias, 51-52 => (fat arrow), 154-156 \ (back slashes), 5 / (forward slashes), 76 A adding compilers to browsers, 6-7 form to client-side todo list application, 242-247 jQuery to client-side todo list application, 240-241 views to todo list application, 268-273 aliases, 46-47 @ alias, 51-52 and alias, 49-50 Boolean aliases, 50-51 not alias, 48-49 or alias, 49-50 and alias, 49-50 anonymous wrapper function, 20-22 APIs, writing todo API, 225-226 app server building with Node.js, 199-213 testing with Node.js, 214-215 278 arguments arguments, 70-72 browsers, in-browser compilation, 6-7 default arguments, 72-75 build task (Cake), 167 splats, 75-79 building arithmetic operators, 33-35 objects, 96-101 arrays, 81-90 todo list application destructing assignment, 86-90 client-side, 237-252 iterating, 105-106 controller, cleaning up, 232-236 slicing, 92-94 Express, setting up, 218-222 swapping assignment, 85-86 MongoDB, setting up, 222-225 testing inclusion, 83-84 server-side, 217 values todo API, writing, 225-226 injecting, 95-96 by keyword, 106-107 replacing, 94-95 C Ashkenas, Jeremy, 255 assignment operators, 35-39 asynchronous programming, 151-154 attributes, retrieving from objects, 101-103 B Cake, 161 tasks invoking, 167-169 options, 163-167 running, 163 writing, 162-163 back slashes (\), 5 Cakefiles, 161 Backbone, 255-256 calling functions, 68-70 configuring for todo list application, 256-259 todo model, writing, 256-259 todos creating, 265-268 listing with view, 263-265 bare flag, 9-10 beforeEach function, 181-187 binding, 151-158 block comments, 30 Boolean aliases, 50-51 Bootstrap, building client-side todo list application, 237-240 classes defining, 123-124 extending, 137-145 inheritance, 137-145 scope, 127-137 class-level functions, 145-150 clean task (Cake), 167 cleaning up todo list application controller, 232-236 client-side todo list application, building, 237-252 closing REPL, 5 Express, building todo list application code, not repeating, 68 constructor function, 126-127 coffee command, 8-9 creating objects, 96-101 CoffeeScript, declaring variables, 19-20 custom matchers (Jasmine), defining, 187-190 collections arrays D destructing assignment, 86-90 injecting values, 95-96 iterating, 105-106 replacing values, 94-95 slicing, 92-94 swapping assignment, 85-86 testing inclusion, 83-84 ranges, reverse ranges, 91-92 command-line compilation, 7-8 comments, 29-30 block comments, 30 inline comments, 29-30 comparison operators, 39-42 compile flag, 7-8 compiling command-line compilation, 7-8 in-browser compilation, 6-7 comprehensions, 116-118 concatenation, forward slashes (/), 76 conditional statements declaring variables in CoffeeScript, 19-20 in JavaScript, 18-19 default arguments, 72-75 defining Cake tasks, 162-163 classes, 123-124 functions, 68-70 arguments, 70-72 default arguments, 72-75 parentheses, 72 matchers (Jasmine), 187-190 regular expressions, 31 deleting models from views (todo list application), 273-274 todos in client-side todo list application, 252 “describe” block (Jasmine), writing, 175 if statement, 53-54 destructing assignment, 86-90 if/else if statement, 56-58 do keyword, 119-120 if/else statement, 54-56 dot notation, 101 inline conditionals, 60 switch case statements, 60-63 unless statement, 58-60 configuring Backbone for todo list application, 256-259 Jasmine, 172-175 E executing CoffeeScript files, 11 existential operator, 43-46 Express, building todo list application, 218-222 279 280 extended regular expressions G-H extended regular expressions, 31 extending classes, 137-145 F Hello World program, Node.js, 195-197 heredocs, 28-29 HTML files in-browser compilation, 6-7 fat arrow (=>), 154-156 I flags bare flag, 9-10 compile flag, 7-8 output flag, 9 print flag, 10 watch flag, 10-11 for loops by keyword, 106-107 when keyword, 107, 109-110 form, adding to client-side todo list application, 242-247 function keyword, 16 functions, 65-68 anonymous wrapper function, 20-22 if statement, 53-54 if/else if statement, 56-58 if/else statement, 54-56 in-browser compilation, 6-7 inheritance, 137-145 injecting array values, 95-96 inline comments, 29-30 inline conditionals, 60 installing Jasmine, 172 Node.js, 194-195 interpolation, string interpolation, 23-25 iterating arrays, 105-106 arguments, 70-72 J-K default arguments, 72-75 splats, 75-79 beforeEach, 181-187 binding, 151-158 class-level, 145-150 constructor, 126-127 defining, 68-70, 125-126 overriding, 142-145 prototype functions, 110, 150-151 Jasmine “describe” block, writing, 175 installing, 172 matchers, defining, 187-190 setting up, 172-175 testing with, 175-176 beforeEach function, 181-187 unit testing, 176-181 overriding functions JavaScript new keyword, 124 Backbone, 255-256 todo model, writing, 256-259 todos, listing with a view, 263-265 Node.js, 193-194 Node.js, 193-194 app server building, 199-213 testing, 214-215 Hello World program, 195-197 app server, building, 199-213 installing, 194-195 app server, testing, 214-215 streaming APIs, writing, 197-199 Hello World program, 195-197 installing, 194-195 NPM (Node Package Management), 193 Express, setting up, 218-222 streaming APIs, writing, 197-199 variables, declaring, 18-19 jQuery, adding to client-side todo list application, 240-241 O objects attributes, retrieving, 101-103 keywords, var, 19 building, 96-101 L listing existing todos in todo list application, 247-248 literal strings, 25-28 long options, 163 loops comprehensions, 116-118 do keyword, 119-120 for loops by keyword, 106-107 when keyword, 107, 109-110 until loops, 114-115 while loops, 113-114 M-N destructing assignment, 103-105 iterating, 108-113 operators aliases, 46-47 @ alias, 51-52 and alias, 49-50 Boolean aliases, 50-51 not alias, 48-49 or alias, 49-50 arithmetic operators, 33-35 assignment operators, 35-39 comparison operators, 39-42 existential operator, 43-46 string operators, 42-43 options for Cake tasks, 163-167 or alias, 49-50 MongoDB, setting up, 222-225 output flag, 9 Mongoose, finding todos in todo list application, 227-228 overriding functions, 142-145 281 282 parentheses P parentheses, 16-17 comprehensions, 117 functions, calling, 72 print flag, 10 prototype function, 110 prototype functions, 150-151 Q-R slicing arrays, 92-94 splats, 75-79 streaming APIs, writing with Node.js, 197-199 string interpolation, 23-25 string operators, 42-43 strings heredocs, 28-29 literal strings, 25-28 switch case statements, 60-63 querying todo list application, 227-228 synchronous programming, 151 quitting REPL, 5 syntax function keyword, 16 parentheses, 16-17 ranges, 90-96 reverse ranges, 91-92 regular expressions, extended regular expressions, 31 ranges, 90 significant whitespace, 14-16 T REPL, 3-5 \ (back slashes), 5 Node.js, 194 tasks Cake quitting, 5 replacing array values, 94-95 retrieving attributes from objects, 101-103 reverse ranges, 91-92 running Cake tasks, 163 invoking, 167-169 options, 163-167 running, 163 writing, 162-163 TDD (test-driven development), 171 terminating REPL, 5 S testing with Jasmine, 175-176 scope in classes, 127-137 beforeEach function, 181-187 servers (Node.js), creating, 195-197 matchers, defining, 187-190 server-side, building todo list application, 217 setting up Jasmine, 172-175 short options, 163 significant whitespace, 14-16 TDD, 171 unit testing, 176-181 testing inclusion, Node.js app server, 214-215 283 U todo list application Backbone configuring, 256-259 todos, creating, 265-268 todos, listing with a view, 263-265 client-side building, 237-252 exisiting todos, listing, 247-248 unit testing with Jasmine, 176-181 unless statement, 58-60 until loops, 114-115 updating todo list application, 230-232 todos in client-side todo list application, 248-251 form, creating, 242-247 V jQuery, adding, 240-241 todos, deleting, 252 var keyword, 19 todos, updating, 248-251 variables, declaring controller, cleaning up, 232-236 in CoffeeScript, 19-20 server-side in JavaScript, 18-19 building, 217 todo API, writing, 225-226 todos creating, 228-230 finding, 227-228 views adding to todo list application, 268-273 models, deleting from (todo list application), 273-274 updating, 230-232 W-X-Y-Z views adding, 268-273 watch flag, 10-11 deleting models from, 273-274 when keyword, 109-110 todo list application, building Express, setting up, 218-222 MongoDB, setting up, 222-225 Twitter Bootstrap todo list application client-side, building, 237-240 while loops, 113-114 writing Cake tasks, 162-163 “describe” block (Jasmine), 175 todo API, 225-226 todo model with Backbone, 256-259 This page intentionally left blank

 

pages: 193 words: 36,189

Html5 Boilerplate Web Development by Divya Manian

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

en.wikipedia.org, Firefox, Google Chrome, node package manager, pull request, search engine result page

node.js With the node.js configuration file, the usage is different. The configuration file assumes you are using the Express/Connect framework for managing resource requests for your app. In your server-side app code, you can use the following to start the server: var h5bp = require('h5bp'); var app = express.createServer(); app.use(h5bp.server()); app.listen(3000); This requires you to install the h5bp package using Node Package Manager (NPM) and the express package using the same. The h5bp package has a slew of configurations that will be used when the server is started. If you wish to use only some specific configurations, you can pass them in as options to the server function, as shown in the following code snippet: app.use(h5bp.server({ server: true, setContentType: true, removeEtag: true }); Google App Engine Some websites are also served from Google App Engine (http://code.google.com/appengine/), which requires your website's backend to be written in Java, Python, or Go.

 

pages: 196 words: 58,122

AngularJS by Brad Green, Shyam Seshadri

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

combinatorial explosion, continuous integration, Firefox, Google Chrome, MVC pattern, node package manager, single page application, web application, WebSocket

The tests also act as specification, and thus documentation, for future needs and changes. We at AngularJS have found this to be true, and the entire AngularJS codebase has been developed using TDD. For an uncompiled, dynamic language like JavaScript, we strongly believe that having a good set of unit tests will reduce headaches in the future! So how do we get this awesomeness that is Karma? Well, first ensure that NodeJS is installed on your machine. This comes with NPM (Node Package Manager), which makes it easy to manage and install the thousands of libraries available for NodeJS. Once you have NodeJS and NPM installed, installing Karma is as easy as running: sudo npm install -g karma There you go. You are ready to start Karmaing (I just made that up, please don’t go about using it in real life) in three easy steps! Getting your config file up If you used Yeoman to create your app skeleton, then you already have a ready-made Karma config file waiting for you to use.

 

pages: 420 words: 79,867

Developing Backbone.js Applications by Addy Osmani

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Airbnb, anti-pattern, create, read, update, delete, database schema, Firefox, full text search, Google Chrome, Khan Academy, loose coupling, MVC pattern, node package manager, pull request, side project, single page application, web application

If you are more comfortable in setting up a REST server in another language, this is the API you need to conform to: url HTTP Method Operation /api/books GET Get an array of all books /api/books/:id GET Get the book with id of :id /api/books POST Add a new book and return the book with an id attribute added /api/books/:id PUT Update the book with id of :id /api/books/:id DELETE Delete the book with id of :id The outline for this section looks like this: Install node.js, npm, and MongoDB Install node modules Create a simple web server Connect to the database Create the REST API Install node.js, npm, and MongoDB Download and install node.js from nodejs.org. The node package manager (npm) will be installed as well. Download, install, and run MongoDB from mongodb.org (you need Mongo to be running to store data in a Mongo database). There are detailed installation guides on the website. Install node modules Create a file called package.json in the root of your project. It should look like { "name": "backbone-library", "version": "0.0.1", "description": "A simple library application using Backbone", "dependencies": { "express": "~3.1.0", "path": "~0.4.9", "mongoose": "~3.5.5", "body-parser": "~1.9.1" } } Amongst other things, this file tells npm what the dependencies are for our project.

 

pages: 713 words: 93,944

Seven Databases in Seven Weeks: A Guide to Modern Databases and the NoSQL Movement by Eric Redmond, Jim Wilson, Jim R. Wilson

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Amazon Web Services, create, read, update, delete, data is the new oil, database schema, Debian, domain-specific language, en.wikipedia.org, fault tolerance, full text search, general-purpose programming language, linked data, MVC pattern, natural language processing, node package manager, random walk, recommendation engine, Skype, social graph, web application

Adding single members directly to CouchDB for each line in the file can cause update thrashing, where two band member lines attempt to create/update the same band document at the same time, forcing the system to reinsert when one of them fails CouchDB’s version check. The catch with this strategy is that you’re limited to the constraints of Redis to hold an entire dataset in RAM—though this limit could be overcome by the simple consistent-hashing cluster we saw on Day 2. With our data file in hand, ensure you have Node.js installed as well as the Node Package Manager (npm). Once that’s all done, we need to install three NPM projects: redis, csv, and hiredis (the optional Redis C-driver we learned about yesterday that can greatly speed up Redis interactions). ​​$ npm install hiredis redis csv​​ Then, check that your Redis server is running on the default port 6379, or alter each script’s createClient function to point to your Redis port. You can populate Redis by running the following Node.js script in the same directory as your TSV file, which we assume is named group_membership.tsv.