Node Js Cheat Sheet



  1. Node Js Interview Cheat Sheet
  2. React Js Cheat Sheet Pdf
  3. React Js Cheatsheet
  4. Npm Cheat Sheet
  5. Node Js Cheat Sheet Github

Resource

  1. Node.js Cheat Sheet. If you’ve read this far, you probably already know, but for those intrigued, Node.JS is an evented I/O framework for the V8 JavaScript engine. It’s ideal for writing scalable network programs such as web servers.
  2. NodeJS security cheat sheet¶ Introduction ¶. This cheat sheet lists actions developers can take to develop secure Node.js applications. Node.js applications are increasing in number and they are no different from other frameworks and programming.

Related

Learn how to use JavaScript modules, a way to define reusable logic in your programs.

Basic

Global Objects

console

Timers

Util

Module

Modules

Addons

Buffer/Stream

Buffer

Stream

TTY

Process/Events

Process

Events

Domain

Domain

Crypto

TSL(SSL)

StringDecoder

File

File System

Net

net

UDP / Datagram Sockets

DNS

Text

Path

Query String

punnycode

Readline

HTTP

http

Class: http.Server

Class: http.ServerRequest

Class: http.ServerResponse

Class: http.Agent

Class: http.ClientRequest

http.ClientResponse

Node Js Interview Cheat Sheet

HTTPS

URL

Code

Executing JS

Child Process

Assert

System

Zlib

os

Node Js Cheat Sheet

Debugger

Cluster

3rd Party

Third Party Modules

  • Module Installer: npm
  • HTTP Middleware: Connect
  • Web Framework: Express
  • Web Sockets: Socket.IO
  • HTML Parsing: HTML5
  • mDNS/Zeroconf/Bonjour/li>
  • Serialization: msgpack
  • Scraping: Apricot
  • Debugger: ndb is a CLI debuggerinspector is a web based tool.
  • Testing/TDD/BDD: vows,mocha,mjsunit.runner
  • Setup (Node, NVM, and NPM)
  • Module System

Node.js (Node) is an open source runtime environment backed by a huge developer community. It is often used to prototype web services and backends. Using Node, developers can reusefront-end skills and libraries for the backend. This post is a cheatsheet of common Node tools, commands, concepts, and techniques.

Node Version Manager (NVM)

Node evolves quickly and sometimes new releases break backward compatibility. Thus, you may need to maintain and switch between different versions. The Node Version Manager (NVM) comes to the rescue.Like Ruby’s rvm and Python’s pyenv,NVM allows us to work with multiple Node environments. You can install it from here.

The following commands list all available versions:

Here is how to install new Node versions:

When installing a new Node version, you may want to migrate existingglobal Node packages. This will ensure they’re compatible wit the new version.To do so, use the --reinstall-packages-from=node option:

Switching to another installed version goes like this:

The Node Package Manager (NPM)

NPM is Node’s default package manager and is similar to Ruby’sBundler and Python’s PIP.It comes preinstalled with Node. To create a new project in a folder:

This will create a package.json file which contains all project dependecies and metadata. It can also include a scripts section which predefines command aliases. Here is an example of a package.json file:

Given this sample, we can run the test command alias as follows:

You can modify the package.json file manually, or add new dependencies via the npm install command with the --save flag:

Express

We can also install a library as a “dev” dependency with the --save-dev flag.This is useful for tools which we won’t need in production – e.g. testing libraries. Such dependencies are defined in thedevDependencies section of the packages.json.

All modules are stored in the ./node_modules folder and it shouldbe in your .gitignore. You can reinstall all modules with: npm install.

NPM alllows the installation of global packages. They are not placed in ./node_modules and are shared across all Node environments. In general, you should avoid global packages except for global utilitieslike debuggers, compilers, and performance monitoring tools. The -g flag denotesthat a package is installed globally:

Run, Debug, and Reload

A Node interpreter (REPL) can be started with the node command.This opens up a REPL for running Node commands interactively. To quit we need to type .exit:

Within a Node project folder, you can execute a Node script, which is a JavaScript file.To debug, use the debug parameter, which starts the script in debug mode. Then you can step through thecode via the continue (c), step over/next(n), and step into (s)commands. The repl command allows you to check the values ofvariables and expressions in the respective context. Breakpointsare put directly in the code as debugger statements:

Node does not automatically refresh/reload upon code changesand needs to be restarted. Hence, it is convenient to use the nodemontool which automatically reloads the Node environment. First you need toinstall it globally:

Then you can use it in place of the node command:

Node does not have logical modular constructs like packages or namespaces. Modules are either files in the project folder, or external NPM packages.The latest version of Node does not natively support the ES6 import andexport functionalities. To use them, you need to set-up Babel compilation. Furthermore, most existing JavaScript code usespre-ES6 syntax. Thus, we will overview both ways of working with modules.

Pre-ES6 modules

Before ES6, modules could export a single variable called module.exports. Client modules would use the require function to load its value:

For example, we could define a module in a file ./friends.js:

Now lets import/include friends.js and a 3rd party module/package moment:

ES6 modules

Node Js Cheat Sheet

In ES6, a module can export multiple elements with the export command.A module can optionally have a default export, which is automaticallyimported when you include the module:

Node js express cheat sheet pdf

External modules are loaded via the import command which has several variations.Assuming the previous example is in a file called importExample.js, we could work with it as follows:

Application configuration is often provided in the form of environment variables.Examples of such configuration are: environment identifier (e.g. dev/staging/prod) and databaseconnection url. In Node, environment variables can be accessed through the proces.env object. For example:

If Node is running a script (i.e. not in REPL mode), you can access the special variables__dirname and __filename which denote the paths to the currently executing script/moduleand its directory. This comes handy when accessing resources from relative folders.

The latest versions of Node support ES6 almost fully. However, some features (e.g. ES6-style import/export) are not yet supported. If we want to use them,we’ll have to compile our code to an earlier JavaScript version with Babel.

We need to install it as a dev dependency:

Babel uses presets, which define what code transformations will be applied.Let’s install a basic ES6 preset:

Babel loads the preset from its config file .babelrc. Hence, we should specify it there as:

In the most typical use case, Babel would take a source folder with ES6 code and generatethe compiled output in another folder. If all our code is in the src/ sub-folder, we can compile to the build/ folder as follows:

We can then run the newly generated code in build/ as normal Node code by using thenode or nodemon commands. Babel can monitor for changes, and compileautomatically with the --watch option:

The babel-node command combines compilation and execution in one step. Given a file srct/test.js you can compile and run as:

So how do we run this with nodemon? Here it is:

It is convenient to define command aliases in package.json.Assuming a file src/test.js exists, we can use:

And then we can invoke them with:

NOTE: We could have installed Babel globally, like we did with nodemon.In this case, we would have all babel utilities on the Path, and we would nothave to use relative paths (i.e. ./node_modules/.bin). Both approaches arepossible.

React Js Cheat Sheet Pdf

Many developers prefer statically typed languages like Scala, Java, and C++.While there are compilers from such languages to JavaScript (e.g. TypeScript, GWT, and Scala.js), incorporating type safety into existing JavaScriptcode bases is far from trivial.

Enter Flow! It is a static type checker for JavaScript. Youcan incrementally add Flow type annotations to your JavaScript code instead of rewriting it all in another language.

First, lets install Flow globally:

This will add the flow command to your terminal environment. Then we need to initialiseFlow within the node project directory:

This will create a .flowconfig file with Flow settings.

JavaScript syntax does not support type annotations and adding them would result in syntax errors. One workaround is to add the types as comments which Flow will interpret:

Note the //@flow comment at the beginning of the file. It tells Flow to process the file –otherwise it will ignore it. To analyse the code for type violations, just run flow fromthe project’s folder. This should report all type errors.

Defining type information in comments is not very convenient. We can use Babel to remove the type annotations for us. Given the Babel setup from the previous secion, we also need to install a plugin for Flow:

And then the .babelrc file must be configured to use it:

Now we can use types in the code:

We can also enable Flow to type check how we use 3rd party libraries. There is a centralrepository of type definitions for many popular libraries. It can be accessed via theflow-typed module:

This will enable Flow to dynamically pull library type definitions.

Finally, don’t forget to install a Flow plugin for your favorite editor/IDE to get typehints as you code.

Promises are available in JavaScript and are not specific to Node.However, they are quite important for many Node libraries for async operations, and thus we’ll review them quickly. A promise allows us to work succinctly with async operations without nested boilerplate callbacks.

React Js Cheatsheet

A promise is an instance of class Promise. It is a wrapper of a higher order functionwhich takes two callback functions as parameters called resolve and reject. The functioncalls them when the encapsulated operation succeeds or fails respectively. Thefollowing example shows a promise which succeeds if a random number is less than 0.5:

We can “chain” actions after a promise with the then method, which is also a higher order function.It takes two parameters – a function which is called “on success” and one for failure.Alternatively, we can provide only the “on success” function, and then chain a call to the catch method:

Npm Cheat Sheet

Often, we need to run multiple async operations in a sequence. For example, we cancall a web service, and if successfull make an SQL query, and if successfull …In other words, we need to chain promises. We can easily achieve this by returninga promise from our success-handling function:

Node Js Cheat Sheet Github

Please enable JavaScript to view the comments powered by Disqus.