Node.js – walk-through – Part 1

RESTful = Http Verbs.

Socket.io
Real-time application framework for Node.js
Allows to send messages from one server to multiple connected browsers.
Supports fallback functionality. Means supports old type browsers. Works between Server-Client.

Express.js
REST framework for Node.js, defines page handles for routes.

Node uses Module names as Namespaces.

Node.js is not ideal for large applications, because it has high CPU usage and also high memory data sets. Node.js is not best for CRUD applications, is not really good just for simple Database read/write applications.

Tip: You should keep variables in a scope that is local to the functions that need to use them.

Installing a Module$ npm install <package name>
Sample: $ npm install sax

Uninstalling a Module$ npm uninstall <package name>
$ npm uninstall -g <package name> to remove globally installed package.

Updating a Module$ npm update <package name>

Event-driven or asynchronous programming is a programming style whereby the flow of execution is determined by events. Events are handled by event handlers or event callbacks.

Allowing JavaScript developers to create extremely high performance servers by leveraging Google’s V8 JavaScript engine, and asynchronous I/O.
This project turned the difficult task of writing event-driven server-side applications into an easy one. Node allows you to easily construct fast and scalable network services.

The most significant difference between child_process.spawn and child_process.exec is in what they return –
spawn returns a stream and exec returns a buffer.
spawn is best used to when you want the child process to return a large amount of data to Node – image processing, reading binary data etc.
So what do you use exec for? Use it to run programs that return result statuses, instead of data. to spawn child processes that execute external commands by using the child_process.spawn method.

When you use​ stream.pause();​​ you will not receive any further “data” events.
Readable Stream example; in the second example we specify Encoding type.

Node does not block on I/O,​​ it does not block on read or write commands.
Knowing When the Stream Ends

 The ​transmission control protocol​​ (TCP) is one of the fundamental protocols of the Internet.  It sits on top of the ​Internet protocol​​ (IP) and provides a
transport mechanism for the application layer.

​HTTP​​, for instance, works on top of ​TCP​​, as do many other connection­oriented applications such as iRC,
SMTP, and IMAP.

Lifecycle example of a ​TCP server​​.

​The socket.setKeepAlive() setting periodically sends an empty packet to keep the ​connection alive​​, whereas ​socket.setTimeout​​() is used to define a
local inactivity timeout.

When you get the request event on a server, you don’t immediately get the body of that request​​, simply because it has not arrived yet. But if you want to, ​you can listen for data events​​, or even pipe the request body into a WriteStream, such as a file or a TCP connection.

Piping a File When you browse this movie through web browser, ​the movie should start playing immediately​​, even though it’s not fully loaded.

You can stop HTTP server with this command: ​server.close();

HTTP​​, for instance, solves these problems whereby an application needs a request­ response workflow from a server and request and response messages are clearly delimited.

TCP ​​guarantees that the messages you receive are in order. Remember that TCP guarantees only that the packets are received in order by the application, not that they are received at all. TCP is not message­oriented; it just provides a continuous stream of data.

Printing Server Messages
conn.pipe(process.stdout, {end: false});

TCP is connection ­oriented protocol​​ that provides a reliable, ordered stream of bytes from one network node to another.

User Datagram Protocol ​(UDP), however, is a connection less protocol ​​that does not provide the delivery characteristics of TCP. When sending UDP packets,you are not guaranteed of The order they arrive in or even whether they arrive at all.

Despite these limitations, ​UDP can be quite useful​​; for instance, when you ​need to broadcast messages, you don’t need hard delivery guarantees or message ordering, or when you don’t know the addresses of your peers.

The Node https module extends the functionality of the HTTP module and uses the ​TLS ​​module to provide the ​underlying transport on top of HTTP​​.

devDependecies

Using a logger ​middleware

Some are separate modules that you can glue together, and some, like ​Express.js​​, offer an integrated solution that you can rapidly implement.

WebSocket connection is just a conventional TCP connection between an HTTP server and an HTTP client​​. It’s established using a handshake protocol, which is very similar to an HTTP handshake. The client initializes the connection. To do this, the browser sends a special HTTP/1.1 request to the server, asking it to turn the connection of this request into a WebSockets connection.

The best practice is not to include a ​node_modules ​​folder into ​Git repository ​​when the project is a module that supposed to be use in other application. However, it’s recommended to include ​node_­ modules ​​for deployable applications. This prevents a breakage caused by unfortunate dependency update.

The best debugger is console.log​​(), but sometime we need to see the call stack and orient ourselves in async code a bit more.

send404, ​404 ​​response from node.js

how module.exports works

Any synchronous call will block Node from doing anything until the call has finished. For example, if you’re running an HTTP server, you would take a performance hit if you used require on each incoming request. ​This is typically why require and other synchronous operations ​​are used only when the application initially loads.

Event emitters fire events and include the ability to handle those events when triggered​​. Some important Node API components, such as ​HTTP servers​​, TCP servers, and streams, are ​implemented as event emitters​​. You can also create your own.

Node, like many other languages, provides a ​REPL ​​(​read­eval­print­loop​​) interface, available by running node from the command line without any
arguments.

Cookies​​ are often used by web browsers to ​simulate state ​​because ​HTTP is a stateless protocol​​.

Get and Set a Single Cookie with Node.js HTTP Server

JSON COOKIES The special JSON cookie is prefixed with j:, which informs Connect that it is intended to be serialized JSON. JSON cookies can be either
signed or unsigned.

vhost(): virtual hosting The vhost() (virtual host) middleware component is a simple, lightweight way to route requests via the Host request header. This task is commonly performed by a reverse proxy, which then forwards the request to a web server running locally on a different port​​.

csrf​​(): cross­site request forgery protection The csrf() component works by generating a 24­ character unique ID, the authenticity token, and assigning it to the user’s session as req.session._csrf. This token can then be included as a ​hidden form input named _csrf​​, and the CSRF component can validate the token on submission. This process is repeated for each interaction.

The ​compress​​() component auto detects accepted encodings via the Accept­ Encoding header field. If this field isn’t present, the identity encoding is used, meaning the response is untouched. Otherwise, if the field contains ​gzip, deflate​​, or both, the response will be compressed.

Practically speaking, ​TDD and BDD are largely the same thing, with the differences mostly being in the language used to describe the tests​​, as you’ll see when we go through some examples.

in MVC web applications, the user will typically request a resource from the server, which will cause the controller to request application data from the model and then pass the data to the view, which will finally format the data for the end user.

noSQL databases, has table, key/value pair

Database usage and decision on Web Applications

Cross Browser Testing: https://ci.testling.com/

Securing user passwords

Error handling middle-ware in Connect

Authenticating user logins

NODE_ENV, process.env object

req.param()

node specific cloud­hosting and ide services

Auto­reload of files in Node.js

In addition to using all CPU cores, you’ll want to avoid using Node to host static files for high ­volume production sites. Node is geared toward interactive applications, such as web applications and TCP / IP protocols, and it can’t serve static files as efficiently as software optimized to do only that.

For serving static files you’ll want to ​use technologies like Nginx (http://nginx.org/en/), which specializes in serving static files​​.

Alternatively, you could upload all your ​static files to a content delivery network ( CDN ), like Amazon S3 (http://aws.amazon.com/s3/), and reference those files in your application. ​​In this section, we’ll cover some server uptime and performance tips:

Using Upstart to keep your application up and running through restarts and crashes Using Node’s cluster API to utilize multi core processors Serving Node application static files using Nginx.

NGINX, Inchttps://www.youtube.com/user/NginxInc/videos

Most modern computer CPU’s have multiple cores, but a Node process uses only one of them when running​​. If you were hosting a Node application on a server and wanted to maximize the server’s usage, ​you could manually start multiple instances of your application on different TCP / IP ports and use a load balancer to distribute web traffic to these different instances​​, but that’s laborious to set up.

To make it easier to use multiple cores for a single application, the ​cluster API ​​was added to Node. This API makes it easy for your application to simultaneously run multiple “workers” on different cores that each do the same thing and respond to the same TCP / IP port. Figure 12.4 shows how an application’s processing would be organized using the cluster API on a four­core processor.

A demonstration of Node’s cluster API

ngingx

Leave a Reply

Your email address will not be published. Required fields are marked *