JavaScript
/*
* ———————–
* Ember.js Cheatsheet
* ———————–
*
* Docs: https://guides.emberjs.com/
* Quick start: https://guides.emberjs.com/current/getting-started/quick-start/
*
* Table of contents
* ——————-
* 01 | Installation
* 02 | Ember CLI
* 03 | Directory layout
* 04 | Routes
* 05 | Templates
* 06 | Components
* 07 | Models
* 08 | Services
* 09 | Testing
* 10 | Addons
* 11 | Configuration
* 12 | Community
*
*/
/*
* 01 | Installation
* ————————————————————–
* Getting started with Ember is easy. Ember projects are created
* and managed through our command line build tool Ember CLI.
*/
“`
npm install -g ember-cli
ember new <application-name>
ember serve
“`
/*
* 02 | Ember CLI
* ————————————————————–
* Ember CLI is the Ember.js command line utility that provides a
* fast Broccoli-powered asset pipeline, a strong conventional
* project structure, and a powerful addon system for extension.
*
* Among the principal features of Ember CLI are:
– Project/Addon creation: create new projects quickly without having to worry about project structure;
– Build pipeline: asset compilation, finger-printing and more out of the box;
– Generators: use the built-in generators and get files that follow the latest practices, and matching tests;
– Ember Addons: extend both your application and Ember CLI itself with community solutions. Also an excellent
way to easily integrate 3rd party libraries into your Ember app.
*/
Basic commands
Command | Aliases | Description
————————————————–
“`
ember new | | Create new project with the provided name (ex. ember new <app-name>)
ember server | ember s | Starts development server (default port is 4200)
ember test | ember t | Run tests in CI mode
ember generate | ember g | Run generator
ember destroy | ember d | Remove code created by generator
ember help | ember h | Get more info on available cli command
ember install | ember i | Install given addon into project and save to package.json
ember | | List available cli commands
“`
Useful commands
“`
ember s –proxy <proxy-url>
ember s –port <port>
“`
/*
* 03 | Directory Layout
* ————————————————————–
*
* Layout of the root folder */
app/
` This is where folders and files for models, components, routes, templates and styles are stored. The majority of your coding on an Ember project happens in this folder. `
config/
` The config directory contains the environment.js where you can configure settings for your app. `
node_modules/
` This directory is from npm. npm is the package manager for Node.js. Ember is built with Node and uses a variety of Node.js modules for operation. The package.json file maintains the list of current npm dependencies for the app. Any Ember CLI addons you install will also show up here. `
public/
` This directory contains assets such as images and fonts. `
vendor/
` This directory is where front-end dependencies (such as JavaScript or CSS) that are not managed by NPM go. `
tests/testem.js
` Automated tests for our app go in the tests folder, and Ember CLI’s test runner testem is configured in testem.js. `
ember-cli-build.js
` This file describes how Ember CLI should build our app. `
package.json
` Packages listed in package.json are installed in the node_modules directory. `
/*
* Layout of the app directory */
adapters/
` Adapters with the convention adapter-name.js. `
components/
` Components with the convention component-name.js. Components must have a dash in their name. So blog-post is an acceptable name, but post is not. `
controllers/
` Controllers behave like a specialized type of Component that is rendered by the router when entering a Route. `
helpers/
` Helpers with the convention helper-name.js. Helpers must have a dash in their name. Remember that you must register your helpers by exporting makeBoundHelper or calling registerBoundHelper explicitly. `
models/
` Models with the convention model-name.js. `
routes/
` Routes with the convention route-name.js. Child routes are defined in sub-directories, parent/child.js. To provide a custom implementation for generated routes (equivalent to App.Route when using globals), use app/routes/basic.js. `
styles/
` Contains your stylesheets, whether SASS, LESS, Stylus, Compass, or plain CSS (though only one type is allowed, see Asset Compilation). These are all compiled into <app-name>.css. `
templates/
` Your HTMLBars templates. These are compiled to /dist/assets/<app-name>.js. The templates are named the same as their filename, minus the extension (i.e. templates/foo/bar.hbs -> foo/bar). `
serializers/
` Serializers for your models or adapter, where model-name.js or adapter-name.js. `
utils/
` Utility modules with the convention utility-name.js. `
router.js
` Your route configuration. The routes defined here correspond to routes in app/routes/. `
/*
* 03 | Routes
* ————————————————————–
*
* When your application starts, the router matches the current URL to the routes that you’ve defined.
* The routes, in turn, are responsible for displaying templates, loading data, and setting up application state.
*
* > ember g route <route-name>
*/
import Route from ‘@ember/routing/route’;
export default Route.extend({
model() {
// Typically, the model hook should return an Ember Data record,
// but it can also return any promise object (Ember Data records are
// promises), or a plain JavaScript object or array. Ember will wait
// until the data finishes loading (until the promise is resolved)
// before rendering the template.
}
});
/*
* 04 | Templates
* ————————————————————–
*
* Ember uses the Handlebars templating library to power your app’s user
* interface. Handlebars templates contain static HTML and dynamic
* content inside Handlebars expressions, which are invoked with
* double curly braces: {{}}.
*
* Templates are backed with a context. A context is an object from
* which Handlebars expressions read their properties. In Ember this
* is often a component. For templates rendered by a route (like application.hbs),
* the context is a controller.
*
* > ember g template <template-name>
*/
// Here’s an basic exmpale of a template
“`hbs
Hello, <strong>{{firstName}} {{lastName}}</strong>!
“`
/*
* 05 | Components
* ————————————————————–
*
* Ember components are used to encapsulate markup and style into
* reusable content. Components consist of two parts: a JavaScript
* component file that defines behavior, and its accompanying Handlebars
* template that defines the markup for the component’s UI.
*
* > ember g component <component-name>
*/
// app/components/<component-name>.js
import Component from ‘@ember/component’;
export default Component.extend({
});
// app/templates/components/<component-name>.hbs
“`hbs
{{yield}}
“`
/*
* Actions
*
* Provide a means to communicate events and changes
*/
// app/components/rental-listing.js
import Component from ‘@ember/component’;
export default Component.extend({
isWide: false,
actions: {
toggleImageSize() {
this.toggleProperty(‘isWide’);
}
}
});
// Actions can be attached to DOM elements inside templates using the {{action}} helper
“` app/templates/components/rental-listing.hbs
<article class=”listing”>
<a {{action ‘toggleImageSize’}} class=”image {{if isWide “wide”}}”>
<img src=”http://www.fillmurray.com/200/300″ alt=””>
</a>
</article>
“`
/*
* Component lifecycle
*
* As components are rendered, re-rendered and finally removed, Ember provides
* lifecycle hooks that allow you to run code at specific times in a component’s life.
*/
On Initial Render
1 init
2 didReceiveAttrs
3 willRender
4 didInsertElement // Good place to integrate with 3rd party libraries
5 didRender
On Re-Render
1 didUpdateAttrs
2 didReceiveAttrs
3 willUpdate
4 willRender
5 didUpdate
6 didRender
On Component Destroy
1 willDestroyElement
2 willClearRender
2 didDestroyElement
/*
* Block params
*
* Components can have properties passed in, but they can also return
* output to be used in a block expression.
*/
// Here an entire blog post model is being passed to the component as a
// single component property. In turn the component is returning values using yield.
“` app/templates/index.hbs
{{blog-post post=model}}
“`
“` app/templates/components/blog-post.hbs
{{yield post.title post.body post.author}}
“`
// The block expression can then use block params to bind names to any yielded
// values for use in the block. This allows for template customization when using
// a component, where the markup is provided by the consuming template, but any
// event handling behavior implemented in the component is retained such as click() handlers.
“` app/templates/index.hbs
{{#blog-post post=model as |title body author|}}
<h2>{{title}}</h2>
<p class=”author”>by {{author}}</p>
<p class=”post-body”>{{body}}</p>
{{/blog-post}}
“`
// The names are bound in the order that they are passed to yield in the component template.
/*
* 06 | Models
* ————————————————————–
*
* Models are objects that represent the underlying data that your application
* presents to the user. Different apps will have very different models,
* depending on what problems they’re trying to solve.
*
* Ember Data, included by default when you create a new application,
* is a library that integrates tightly with Ember to make it easy to
* retrieve models from your server as JSON, save updates back to the server,
* and create new models in the browser.
*
* > ember g model <model-name>
*/
import DS from ’ember-data’;
import { computed } from ‘@ember/object’;
const { attr, Model } = DS;
export default Model.extend({
firstName: attr(‘string’),
lastName: attr(‘string’),
birthday: attr(‘date’),
// Computed properties
// These are effectively fuctions declared as properties. The function’s result
// will recompute every time one of the provided ‘dependent keys’ changes.
fullName: computed(‘firstName’, ‘lastName’, function() {
let firstName = this.get(‘firstName’);
let lastName = this.get(‘lastName’);
return `${firstName} ${lastName}`;
})
});
/*
* 07 | Services
* ————————————————————–
*
* A Service is an Ember object that lives for the duration of the application, and can
* be made available in different parts of your application. Services are useful for
* features that require shared state or persistent connections.
*
* Example uses of services might include:
*
* – User/session authentication.
* – Geolocation.
* – WebSockets.
* – Server-sent events or notifications.
* – Server-backed API calls that may not fit Ember Data.
* – Third-party APIs.
* – Logging.
*
* > ember g service <service-name>
*/
/*
* Defining services
*
* Like any Ember object, a service is initialized and can have properties and
* methods of its own. Below, the shopping cart service manages an items array
* that represents the items currently in the shopping cart.
*/
// app/services/shopping-cart.js
import Service from ‘@ember/service’;
export default Service.extend({
items: null,
init() {
this._super(…arguments);
this.set(‘items’, []);
},
remove(item) {
this.get(‘items’).removeObject(item);
}
});
/*
* Accessing services
*
* To access a service, you can inject it in any object such as a component or another
* service using the `inject` function from the `@ember/service` module.
*/
// app/components/cart-contents.js
import Component from ‘@ember/component’;
import { inject } from ‘@ember/service’;
export default Component.extend({
shoppingCart: inject() // will load the service in file /app/services/shopping-cart.js
actions: {
remove(item) {
this.get(‘shoppingCart’).remove(item);
}
}
});
// Once injected into a component, a service can also be used in the template.
// Note cart being used below to get data from the cart.
“`hbs app/templates/components/cart-contents.hbs
<ul>
{{#each cart.items as |item|}}
<li>
{{item.name}}
<button {{action “remove” item}}>Remove</button>
</li>
{{/each}}
</ul>
“`
/*
* 08 | Testing
* ————————————————————–
*
* Testing is a core part of the Ember framework and its development cycle.
*
* > ember g acceptance-test <test-name>
* > ember g integration-test <test-name>
* > ember g unit-test <test-name>
* > ember t –server
* > ember s && visit localhost:4200/tests
*/
/*
* Acceptance & application tests
*
* In these kinds of tests, we interact with the application in the same ways that a
* user would, such as filling out form fields and clicking buttons. Application
* tests ensure that the interactions within a project are basically functional, the
* core features of a project have not regressed, and the project’s goals are being met.
*
* Some useful helpers from ‘@ember/test-helpers’:
* – `click(selector)`
* Clicks an element and triggers any actions triggered by the element’s click event and
* returns a promise that fulfills when all resulting async behavior is complete.
*
* – `fillIn(selector, value)`
* Fills in the selected input with the given value and returns a promise that
* fulfills when all resulting async behavior is complete. Works with <select> elements
* as well as <input> elements. Keep in mind that with <select> elements, value must be set
* to the value of the <option> tag, rather than its content (for example, true rather than “Yes”).
*
* – `triggerKeyEvent(selector, type, keyCode)`
* Simulates a key event type, e.g. keypress, keydown, keyup with the desired keyCode on element found by the selector.
*
* – `triggerEvent(selector, type, options)`
* Triggers the given event, e.g. blur, dblclick on the element identified by the provided selector.
*
* – `visit(url)`
* Visits the given route and returns a promise that fulfills when all resulting async behavior is complete.
*
* – `currentURL()`
* Returns the current URL.
*
* – `find(selector, context)`
* Finds an element within the app’s root element and within the context (optional). Scoping to the
* root element is especially useful to avoid conflicts with the test framework’s reporter, and this
* is done by default if the context is not specified.
*
* – `findAll(selector)`
* Find all elements matched by the given selector. Equivalent to calling querySelectorAll() on the
* test root element. Returns an array of matched elements.
*
*/
import { module, test } from ‘qunit’;
import { setupApplicationTest } from ’ember-qunit’;
import { visit, fillIn, click } from ‘@ember/test-helpers’;
module(‘Acceptance | posts’, function(hooks) {
// `setupApplicationTest` deals with application setup and teardown.
setupApplicationTest(hooks);
test(‘should add new post’, async function(assert) {
await visit(‘/posts/new’);
await fillIn(‘input.title’, ‘My new post’);
await click(‘button.submit’);
const title = this.element.querySelector(‘ul.posts li:first’).textContent;
assert.equal(title, ‘My new post’);
});
});
/*
* Integration & rendering tests
*
* Rendering Tests are, as the name suggests, rendering components and helpers
* by verifying the correct behaviour when the component or helper interacts
* with the system in the same way that it will within the context of the application,
* including being rendered from a template and receiving Ember’s lifecycle hooks.
*
* If we need to test the interactions between various parts of the application,
* such as behaviour between UI controls we can utilize Rendering Tests.
*/
// app/components/pretty-color.js
import Component from ‘@ember/component’;
import { computed } from ‘@ember/object’;
export default Component.extend({
attributeBindings: [‘style’],
style: computed(‘name’, function() {
const name = this.get(‘name’);
return `color: ${name}`;
})
});
// tests/integration/components/pretty-color-test.js
import { module, test } from ‘qunit’;
import { setupRenderingTest } from ’ember-qunit’;
import { render } from ‘@ember/test-helpers’;
import hbs from ‘htmlbars-inline-precompile’;
module(‘Integration | Component | pretty color’, function(hooks) {
// Make sure to call the setupRenderingTest function together with the hooks
// parameter first in your new module. This will do the necessary setup for
// testing your component for you, including setting up a way to access the
// rendered DOM of your component later on in the test, and cleaning up
// once your tests in this module are finished.
setupRenderingTest(hooks);
test(‘it renders’, async function(assert) {
assert.expect(2);
// set the outer context to red
this.set(‘colorValue’, ‘red’);
await render(hbs`{{pretty-color name=colorValue}}`);
assert.equal(this.element.querySelector(‘div’).getAttribute(‘style’), ‘color: red’, ‘starts as red’);
this.set(‘colorValue’, ‘blue’);
assert.equal(this.element.querySelector(‘div’).getAttribute(‘style’), ‘color: blue’, ‘updates to blue’); });
});
// Stubbing services
//
// In cases where components have dependencies on Ember services, it is
// possible to stub these dependencies for rendering tests. You stub Ember
// services by using the built-in register() function to register your
// stub service in place of the default.
import { module, test } from ‘qunit’;
import { setupRenderingTest } from ’ember-qunit’;
import { render } from ‘@ember/test-helpers’;
import hbs from ‘htmlbars-inline-precompile’;
import Service from ‘@ember/service’;
//Stub location service
const locationStub = Service.extend({
city: ‘New York’,
country: ‘USA’,
currentLocation: {
x: 1234,
y: 5678
},
getCurrentCity() {
return this.get(‘city’);
},
getCurrentCountry() {
return this.get(‘country’);
}
});
module(‘Integration | Component | location indicator’, function(hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function(assert) {
this.owner.register(‘service:location-service’, locationStub);
});
test(‘should reveal current location’, async function(assert) {
await render(hbs`{{location-indicator}}`);
assert.equal(this.element.textContent.trim(),
‘You currently are located in New York, USA’);
});
});
/*
* Unit & container tests
*
* Unit tests (as well as container tests) are generally used to test a
* small piece of code and ensure that it is doing what was intended.
*/
// app/services/some-thing.js
import Service from ‘@ember/service’;
export default Service.extend({
foo: ‘bar’,
testMethod() {
this.set(‘foo’, ‘baz’);
}
});
// tests/unit/services/some-thing-test.js
import { module, test } from ‘qunit’;
import { setupTest } from ’ember-qunit’;
module(‘Unit | Service | some thing’, function(hooks) {
// The `setupTest` helper provides us with some conveniences, such as the `this.owner` object,
// that helps us to create or lookup objects which are needed to setup our test.
// In this example, we use the `this.owner` object to lookup the service instance that
// becomes our test subject: `someThing`. Note that in a unit test you can customize any
// object under test by setting its properties accordingly. We can use the `set` method
// of the test object to achieve this.
setupTest(hooks);
test(‘should update foo on testMethod’, function(assert) {
const someThing = this.owner.lookup(‘service:some-thing’);
someThing.testMethod();
assert.equal(someThing.get(‘foo’), ‘baz’);
});
});
/*
* Running tests
*
* Run your tests with `ember test` on the command-line. You can re-run your tests on
* every file-change with `ember test –server`.
*
* Tests can also be executed when you are running a local development server
* (started by running `ember server`), at the `/tests` URI which renders the `tests/index.html` template.
*/
“`
ember test
ember test –server
ember test –filter=”dashboard”
run ember server then visit http://localhost:4200/tests
“`
/*
* 09 | Addons
* ————————————————————–
*
* Ember has a rich ecosystem of addons that can be easily added to projects.
* Addons provide a wide range of functionality to projects, often saving time and
* letting you focus on your project.
*
* To browse addons, visit the [EmberObserver](https://emberobserver.com/) website. It catalogs and categorizes Ember
* addons that have been published to NPM and assigns them a score based on a variety of criteria.
*
* > ember install <addont-name>
*/
/*
* 10 | Configuration
* ————————————————————–
*
* Ember CLI ships with support for managing your application’s environment. Ember CLI
* will setup a default environment config file at config/environment. Here, you can define
* an ENV object for each environment, which are currently limited to three: development,
* test, and production.
*/
// The ENV object has three important keys:
// – `EmberENV` can be used to define Ember feature flags (see the Feature Flags guide).
// – `APP` can be used to pass flags/options to your application instance.
// – `environment` contains the name of the current environment (development,production or test).
// You can access these environment variables in your application code by importing from `your-application-name/config/environment`.
import ENV from ‘your-application-name/config/environment’;
if (ENV.environment === ‘development’) {
// …
}
/*
* 11 | Community
* ————————————————————–
*
* Ember’s secret sauce
*
* more at [Ember Community Page](https://emberjs.com/community/)
*
*/
// Ember Discussion Forum
//
// url: http://discuss.emberjs.com/
//
// A great venue for discussing things like features, architecture, and best practices
// and a great place to ask questions (and get great answers from Ember Core Team members
// and other members of the community)
// Ember Community Slack
//
// url: https://embercommunity.slack.com/
//
// Use the Slackin app to receive an invitation.
// Ember Times
//
// url: https://the-emberjs-times.ongoodbits.com/
//
// Follow the progress of new features in the Ember ecosystem, requests for community
// input (RFCs), and calls for contributors
// Ember Weekly
//
// url: http://www.emberweekly.com/
//
// A curated list of Ember learning resources (podcasts, videos, blog posts, books, and more)
// Official Ember Blog
//
// url: https://emberjs.com/blog/
//
// Big announcements like new Ember.js version release notes or State of the Union information
// Ember Github
//
// url: https://github.com/emberjs/
// Ember Meetups
//
// url: https://emberjs.com/community/meetups/
/* *******************************************************************************************
* SYNOPSIS
* http://nodejs.org/api/synopsis.html
* ******************************************************************************************* */
var http = require(‘http’);
// An example of a web server written with Node which responds with ‘Hello World’.
// To run the server, put the code into a file called example.js and execute it with the node program.
http.createServer(function (request, response) {
response.writeHead(200, {‘Content-Type’: ‘text/plain’});
response.end(‘Hello World\n’);
}).listen(8124);
console.log(‘Server running at http://127.0.0.1:8124/’);
/* *******************************************************************************************
* GLOBAL OBJECTS
* http://nodejs.org/api/globals.html
* ******************************************************************************************* */
// In browsers, the top-level scope is the global scope.
// That means that in browsers if you’re in the global scope var something will define a global variable.
// In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.
__filename; // The filename of the code being executed. (absolute path)
__dirname; // The name of the directory that the currently executing script resides in. (absolute path)
module; // A reference to the current module. In particular module.exports is used for defining what a module exports and makes available through require().
exports; // A reference to the module.exports that is shorter to type.
process; // The process object is a global object and can be accessed from anywhere. It is an instance of EventEmitter.
Buffer; // The Buffer class is a global type for dealing with binary data directly.
/* *******************************************************************************************
* CONSOLE
* http://nodejs.org/api/console.html
* ******************************************************************************************* */
console.log([data], […]); // Prints to stdout with newline.
console.info([data], […]); // Same as console.log.
console.error([data], […]); // Same as console.log but prints to stderr.
console.warn([data], […]); // Same as console.error.
console.dir(obj); // Uses util.inspect on obj and prints resulting string to stdout.
console.time(label); // Mark a time.
console.timeEnd(label); // Finish timer, record output.
console.trace(label); // Print a stack trace to stderr of the current position.
console.assert(expression, [message]); // Same as assert.ok() where if the expression evaluates as false throw an AssertionError with message.
/* *******************************************************************************************
* TIMERS
* http://nodejs.org/api/timers.html
* ******************************************************************************************* */
setTimeout(callback, delay, [arg], […]); // To schedule execution of a one-time callback after delay milliseconds. Optionally you can also pass arguments to the callback.
clearTimeout(t); // Stop a timer that was previously created with setTimeout().
setInterval(callback, delay, [arg], […]); // To schedule the repeated execution of callback every delay milliseconds. Optionally you can also pass arguments to the callback.
clearInterval(t); // Stop a timer that was previously created with setInterval().
setImmediate(callback, [arg], […]); // To schedule the “immediate” execution of callback after I/O events callbacks and before setTimeout and setInterval.
clearImmediate(immediateObject); // Stop a timer that was previously created with setImmediate().
unref(); // Allow you to create a timer that is active but if it is the only item left in the event loop, node won’t keep the program running.
ref(); // If you had previously unref()d a timer you can call ref() to explicitly request the timer hold the program open.
/* *******************************************************************************************
* MODULES
* http://nodejs.org/api/modules.html
* ******************************************************************************************* */
var module = require(‘./module.js’); // Loads the module module.js in the same directory.
module.require(‘./another_module.js’); // load another_module as if require() was called from the module itself.
module.id; // The identifier for the module. Typically this is the fully resolved filename.
module.filename; // The fully resolved filename to the module.
module.loaded; // Whether or not the module is done loading, or is in the process of loading.
module.parent; // The module that required this one.
module.children; // The module objects required by this one.
exports.area = function (r) {
return Math.PI * r * r;
};
// If you want the root of your module’s export to be a function (such as a constructor)
// or if you want to export a complete object in one assignment instead of building it one property at a time,
// assign it to module.exports instead of exports.
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}
/* *******************************************************************************************
* PROCESS
* http://nodejs.org/api/process.html
* ******************************************************************************************* */
process.on(‘exit’, function(code) {}); // Emitted when the process is about to exit
process.on(‘uncaughtException’, function(err) {}); // Emitted when an exception bubbles all the way back to the event loop. (should not be used)
process.stdout; // A writable stream to stdout.
process.stderr; // A writable stream to stderr.
process.stdin; // A readable stream for stdin.
process.argv; // An array containing the command line arguments.
process.env; // An object containing the user environment.
process.execPath; // This is the absolute pathname of the executable that started the process.
process.execArgv; // This is the set of node-specific command line options from the executable that started the process.
process.arch; // What processor architecture you’re running on: ‘arm’, ‘ia32’, or ‘x64’.
process.config; // An Object containing the JavaScript representation of the configure options that were used to compile the current node executable.
process.pid; // The PID of the process.
process.platform; // What platform you’re running on: ‘darwin’, ‘freebsd’, ‘linux’, ‘sunos’ or ‘win32’.
process.title; // Getter/setter to set what is displayed in ‘ps’.
process.version; // A compiled-in property that exposes NODE_VERSION.
process.versions; // A property exposing version strings of node and its dependencies.
process.abort(); // This causes node to emit an abort. This will cause node to exit and generate a core file.
process.chdir(dir); // Changes the current working directory of the process or throws an exception if that fails.
process.cwd(); // Returns the current working directory of the process.
process.exit([code]); // Ends the process with the specified code. If omitted, exit uses the ‘success’ code 0.
process.getgid(); // Gets the group identity of the process.
process.setgid(id); // Sets the group identity of the process.
process.getuid(); // Gets the user identity of the process.
process.setuid(id); // Sets the user identity of the process.
process.getgroups(); // Returns an array with the supplementary group IDs.
process.setgroups(grps); // Sets the supplementary group IDs.
process.initgroups(user, extra_grp); // Reads /etc/group and initializes the group access list, using all groups of which the user is a member.
process.kill(pid, [signal]); // Send a signal to a process. pid is the process id and signal is the string describing the signal to send.
process.memoryUsage(); // Returns an object describing the memory usage of the Node process measured in bytes.
process.nextTick(callback); // On the next loop around the event loop call this callback.
process.maxTickDepth; // Callbacks passed to process.nextTick will usually be called at the end of the current flow of execution, and are thus approximately as fast as calling a function synchronously.
process.umask([mask]); // Sets or reads the process’s file mode creation mask.
process.uptime(); // Number of seconds Node has been running.
process.hrtime(); // Returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array.
/* *******************************************************************************************
* CHILD PROCESS
* http://nodejs.org/api/child_process.html
* ******************************************************************************************* */
// Node provides a tri-directional popen facility through the child_process module.
// It is possible to stream data through a child’s stdin, stdout, and stderr in a fully non-blocking way.
ChildProcess; // Class. ChildProcess is an EventEmitter.
child.stdin; // A Writable Stream that represents the child process’s stdin
child.stdout; // A Readable Stream that represents the child process’s stdout
child.stderr; // A Readable Stream that represents the child process’s stderr.
child.pid; // The PID of the child process
child.connected; // If .connected is false, it is no longer possible to send messages
child.kill([signal]); // Send a signal to the child process
child.send(message, [sendHandle]); // When using child_process.fork() you can write to the child using child.send(message, [sendHandle]) and messages are received by a ‘message’ event on the child.
child.disconnect(); // Close the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive.
child_process.spawn(command, [args], [options]); // Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.
child_process.exec(command, [options], callback); // Runs a command in a shell and buffers the output.
child_process.execFile(file, [args], [options], [callback]); // Runs a command in a shell and buffers the output.
child_process.fork(modulePath, [args], [options]); // This is a special case of the spawn() functionality for spawning Node processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in.
/* *******************************************************************************************
* UTIL
* http://nodejs.org/api/util.html
* ******************************************************************************************* */
// These functions are in the module ‘util’. Use require(‘util’) to access them.
util.format(format, […]); // Returns a formatted string using the first argument as a printf-like format. (%s, %d, %j)
util.debug(string); // A synchronous output function. Will block the process and output string immediately to stderr.
util.error([…]); // Same as util.debug() except this will output all arguments immediately to stderr.
util.puts([…]); // A synchronous output function. Will block the process and output all arguments to stdout with newlines after each argument.
util.print([…]); // A synchronous output function. Will block the process, cast each argument to a string then output to stdout. (no newlines)
util.log(string); // Output with timestamp on stdout.
util.inspect(object, [opts]); // Return a string representation of object, which is useful for debugging. (options: showHidden, depth, colors, customInspect)
util.isArray(object); // Returns true if the given “object” is an Array. false otherwise.
util.isRegExp(object); // Returns true if the given “object” is a RegExp. false otherwise.
util.isDate(object); // Returns true if the given “object” is a Date. false otherwise.
util.isError(object); // Returns true if the given “object” is an Error. false otherwise.
util.promisify(fn) // Takes a function whose last argument is a callback and returns a version that returns promises.
util.inherits(constructor, superConstructor); // Inherit the prototype methods from one constructor into another.
/* *******************************************************************************************
* EVENTS
* http://nodejs.org/api/events.html
* ******************************************************************************************* */
// All objects which emit events are instances of events.EventEmitter. You can access this module by doing: require(“events”);
// To access the EventEmitter class, require(‘events’).EventEmitter.
// All EventEmitters emit the event ‘newListener’ when new listeners are added and ‘removeListener’ when a listener is removed.
emitter.addListener(event, listener); // Adds a listener to the end of the listeners array for the specified event.
emitter.on(event, listener); // Same as emitter.addListener().
emitter.once(event, listener); // Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.
emitter.removeListener(event, listener); // Remove a listener from the listener array for the specified event.
emitter.removeAllListeners([event]); // Removes all listeners, or those of the specified event.
emitter.setMaxListeners(n); // By default EventEmitters will print a warning if more than 10 listeners are added for a particular event.
emitter.listeners(event); // Returns an array of listeners for the specified event.
emitter.emit(event, [arg1], [arg2], […]); // Execute each of the listeners in order with the supplied arguments. Returns true if event had listeners, false otherwise.
EventEmitter.listenerCount(emitter, event); // Return the number of listeners for a given event.
/* *******************************************************************************************
* STREAM
* http://nodejs.org/api/stream.html
* ******************************************************************************************* */
// A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is stdout.
// Streams are readable, writable, or both. All streams are instances of EventEmitter.
// The Readable stream interface is the abstraction for a source of data that you are reading from.
// In other words, data comes out of a Readable stream.
// A Readable stream will not start emitting data until you indicate that you are ready to receive it.
// Examples of readable streams include: http responses on the client, http requests on the server, fs read streams
// zlib streams, crypto streams, tcp sockets, child process stdout and stderr, process.stdin.
var readable = getReadableStreamSomehow();
readable.on(‘readable’, function() {}); // When a chunk of data can be read from the stream, it will emit a ‘readable’ event.
readable.on(‘data’, function(chunk) {}); // If you attach a data event listener, then it will switch the stream into flowing mode, and data will be passed to your handler as soon as it is available.
readable.on(‘end’, function() {}); // This event fires when there will be no more data to read.
readable.on(‘close’, function() {}); // Emitted when the underlying resource (for example, the backing file descriptor) has been closed. Not all streams will emit this.
readable.on(‘error’, function() {}); // Emitted if there was an error receiving data.
// The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.
// This method should only be called in non-flowing mode. In flowing-mode, this method is called automatically until the internal buffer is drained.
readable.read([size]);
readable.setEncoding(encoding); // Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.
readable.resume(); // This method will cause the readable stream to resume emitting data events.
readable.pause(); // This method will cause a stream in flowing-mode to stop emitting data events.
readable.pipe(destination, [options]); // This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
readable.unpipe([destination]); // This method will remove the hooks set up for a previous pipe() call. If the destination is not specified, then all pipes are removed.
readable.unshift(chunk); // This is useful in certain cases where a stream is being consumed by a parser, which needs to “un-consume” some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.
// The Writable stream interface is an abstraction for a destination that you are writing data to.
// Examples of writable streams include: http requests on the client, http responses on the server, fs write streams,
// zlib streams, crypto streams, tcp sockets, child process stdin, process.stdout, process.stderr.
var writer = getWritableStreamSomehow();
writable.write(chunk, [encoding], [callback]); // This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled.
writer.once(‘drain’, write); // If a writable.write(chunk) call returns false, then the drain event will indicate when it is appropriate to begin writing more data to the stream.
writable.end([chunk], [encoding], [callback]); // Call this method when no more data will be written to the stream.
writer.on(‘finish’, function() {}); // When the end() method has been called, and all data has been flushed to the underlying system, this event is emitted.
writer.on(‘pipe’, function(src) {}); // This is emitted whenever the pipe() method is called on a readable stream, adding this writable to its set of destinations.
writer.on(‘unpipe’, function(src) {}); // This is emitted whenever the unpipe() method is called on a readable stream, removing this writable from its set of destinations.
writer.on(‘error’, function(src) {}); // Emitted if there was an error when writing or piping data.
// Duplex streams are streams that implement both the Readable and Writable interfaces. See above for usage.
// Examples of Duplex streams include: tcp sockets, zlib streams, crypto streams.
// Transform streams are Duplex streams where the output is in some way computed from the input. They implement both the Readable and Writable interfaces. See above for usage.
// Examples of Transform streams include: zlib streams, crypto streams.
/* *******************************************************************************************
* FILE SYSTEM
* http://nodejs.org/api/fs.html
* ******************************************************************************************* */
// To use this module do require(‘fs’).
// All the methods have asynchronous and synchronous forms.
fs.rename(oldPath, newPath, callback); // Asynchronous rename. No arguments other than a possible exception are given to the completion callback.Asynchronous ftruncate. No arguments other than a possible exception are given to the completion callback.
fs.renameSync(oldPath, newPath); // Synchronous rename.
fs.ftruncate(fd, len, callback); // Asynchronous ftruncate. No arguments other than a possible exception are given to the completion callback.
fs.ftruncateSync(fd, len); // Synchronous ftruncate.
fs.truncate(path, len, callback); // Asynchronous truncate. No arguments other than a possible exception are given to the completion callback.
fs.truncateSync(path, len); // Synchronous truncate.
fs.chown(path, uid, gid, callback); // Asynchronous chown. No arguments other than a possible exception are given to the completion callback.
fs.chownSync(path, uid, gid); // Synchronous chown.
fs.fchown(fd, uid, gid, callback); // Asynchronous fchown. No arguments other than a possible exception are given to the completion callback.
fs.fchownSync(fd, uid, gid); // Synchronous fchown.
fs.lchown(path, uid, gid, callback); // Asynchronous lchown. No arguments other than a possible exception are given to the completion callback.
fs.lchownSync(path, uid, gid); // Synchronous lchown.
fs.chmod(path, mode, callback); // Asynchronous chmod. No arguments other than a possible exception are given to the completion callback.
fs.chmodSync(path, mode); // Synchronous chmod.
fs.fchmod(fd, mode, callback); // Asynchronous fchmod. No arguments other than a possible exception are given to the completion callback.
fs.fchmodSync(fd, mode); // Synchronous fchmod.
fs.lchmod(path, mode, callback); // Asynchronous lchmod. No arguments other than a possible exception are given to the completion callback.
fs.lchmodSync(path, mode); // Synchronous lchmod.
fs.stat(path, callback); // Asynchronous stat. The callback gets two arguments (err, stats) where stats is a fs.Stats object.
fs.statSync(path); // Synchronous stat. Returns an instance of fs.Stats.
fs.lstat(path, callback); // Asynchronous lstat. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
fs.lstatSync(path); // Synchronous lstat. Returns an instance of fs.Stats.
fs.fstat(fd, callback); // Asynchronous fstat. The callback gets two arguments (err, stats) where stats is a fs.Stats object. fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.
fs.fstatSync(fd); // Synchronous fstat. Returns an instance of fs.Stats.
fs.link(srcpath, dstpath, callback); // Asynchronous link. No arguments other than a possible exception are given to the completion callback.
fs.linkSync(srcpath, dstpath); // Synchronous link.
fs.symlink(srcpath, dstpath, [type], callback); // Asynchronous symlink. No arguments other than a possible exception are given to the completion callback. The type argument can be set to ‘dir’, ‘file’, or ‘junction’ (default is ‘file’) and is only available on Windows (ignored on other platforms)
fs.symlinkSync(srcpath, dstpath, [type]); // Synchronous symlink.
fs.readlink(path, callback); // Asynchronous readlink. The callback gets two arguments (err, linkString).
fs.readlinkSync(path); // Synchronous readlink. Returns the symbolic link’s string value.
fs.unlink(path, callback); // Asynchronous unlink. No arguments other than a possible exception are given to the completion callback.
fs.unlinkSync(path); // Synchronous unlink.
fs.realpath(path, [cache], callback); // Asynchronous realpath. The callback gets two arguments (err, resolvedPath).
fs.realpathSync(path, [cache]); // Synchronous realpath. Returns the resolved path.
fs.rmdir(path, callback); // Asynchronous rmdir. No arguments other than a possible exception are given to the completion callback.
fs.rmdirSync(path); // Synchronous rmdir.
fs.mkdir(path, [mode], callback); // Asynchronous mkdir. No arguments other than a possible exception are given to the completion callback. mode defaults to 0777.
fs.mkdirSync(path, [mode]); // Synchronous mkdir.
fs.readdir(path, callback); // Asynchronous readdir. Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding ‘.’ and ‘..’.
fs.readdirSync(path); // Synchronous readdir. Returns an array of filenames excluding ‘.’ and ‘..’.
fs.close(fd, callback); // Asynchronous close. No arguments other than a possible exception are given to the completion callback.
fs.closeSync(fd); // Synchronous close.
fs.open(path, flags, [mode], callback); // Asynchronous file open.
fs.openSync(path, flags, [mode]); // Synchronous version of fs.open().
fs.utimes(path, atime, mtime, callback); // Change file timestamps of the file referenced by the supplied path.
fs.utimesSync(path, atime, mtime); // Synchronous version of fs.utimes().
fs.futimes(fd, atime, mtime, callback); // Change the file timestamps of a file referenced by the supplied file descriptor.
fs.futimesSync(fd, atime, mtime); // Synchronous version of fs.futimes().
fs.fsync(fd, callback); // Asynchronous fsync. No arguments other than a possible exception are given to the completion callback.
fs.fsyncSync(fd); // Synchronous fsync.
fs.write(fd, buffer, offset, length, position, callback); // Write buffer to the file specified by fd.
fs.writeSync(fd, buffer, offset, length, position); // Synchronous version of fs.write(). Returns the number of bytes written.
fs.read(fd, buffer, offset, length, position, callback); // Read data from the file specified by fd.
fs.readSync(fd, buffer, offset, length, position); // Synchronous version of fs.read. Returns the number of bytesRead.
fs.readFile(filename, [options], callback); // Asynchronously reads the entire contents of a file.
fs.readFileSync(filename, [options]); // Synchronous version of fs.readFile. Returns the contents of the filename. If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
fs.writeFile(filename, data, [options], callback); // Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.
fs.writeFileSync(filename, data, [options]); // The synchronous version of fs.writeFile.
fs.appendFile(filename, data, [options], callback); // Asynchronously append data to a file, creating the file if it not yet exists. data can be a string or a buffer.
fs.appendFileSync(filename, data, [options]); // The synchronous version of fs.appendFile.
fs.watch(filename, [options], [listener]); // Watch for changes on filename, where filename is either a file or a directory. The returned object is a fs.FSWatcher. The listener callback gets two arguments (event, filename). event is either ‘rename’ or ‘change’, and filename is the name of the file which triggered the event.
fs.exists(path, callback); // Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false. (should not be used)
fs.existsSync(path); // Synchronous version of fs.exists. (should not be used)
// fs.Stats: objects returned from fs.stat(), fs.lstat() and fs.fstat() and their synchronous counterparts are of this type.
stats.isFile();
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() // (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()
fs.createReadStream(path, [options]); // Returns a new ReadStream object.
fs.createWriteStream(path, [options]); // Returns a new WriteStream object.
/* *******************************************************************************************
* PATH
* http://nodejs.org/api/fs.html
* ******************************************************************************************* */
// Use require(‘path’) to use this module.
// This module contains utilities for handling and transforming file paths.
// Almost all these methods perform only string transformations.
// The file system is not consulted to check whether paths are valid.
path.normalize(p); // Normalize a string path, taking care of ‘..’ and ‘.’ parts.
path.join([path1], [path2], […]); // Join all arguments together and normalize the resulting path.
path.resolve([from …], to); // Resolves ‘to’ to an absolute path.
path.relative(from, to); // Solve the relative path from ‘from’ to ‘to’.
path.dirname(p); // Return the directory name of a path. Similar to the Unix dirname command.
path.basename(p, [ext]); // Return the last portion of a path. Similar to the Unix basename command.
path.extname(p); // Return the extension of the path, from the last ‘.’ to end of string in the last portion of the path.
path.sep; // The platform-specific file separator. ‘\\’ or ‘/’.
path.delimiter; // The platform-specific path delimiter, ‘;’ or ‘:’.
/* *******************************************************************************************
* HTTP
* http://nodejs.org/api/http.html
* ******************************************************************************************* */
// To use the HTTP server and client one must require(‘http’).
http.STATUS_CODES; // A collection of all the standard HTTP response status codes, and the short description of each.
http.request(options, [callback]); // This function allows one to transparently issue requests.
http.get(options, [callback]); // Set the method to GET and calls req.end() automatically.
server = http.createServer([requestListener]); // Returns a new web server object. The requestListener is a function which is automatically added to the ‘request’ event.
server.listen(port, [hostname], [backlog], [callback]); // Begin accepting connections on the specified port and hostname.
server.listen(path, [callback]); // Start a UNIX socket server listening for connections on the given path.
server.listen(handle, [callback]); // The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object.
server.close([callback]); // Stops the server from accepting new connections.
server.setTimeout(msecs, callback); // Sets the timeout value for sockets, and emits a ‘timeout’ event on the Server object, passing the socket as an argument, if a timeout occurs.
server.maxHeadersCount; // Limits maximum incoming headers count, equal to 1000 by default. If set to 0 – no limit will be applied.
server.timeout; // The number of milliseconds of inactivity before a socket is presumed to have timed out.
server.on(‘request’, function (request, response) { }); // Emitted each time there is a request.
server.on(‘connection’, function (socket) { }); // When a new TCP stream is established.
server.on(‘close’, function () { }); // Emitted when the server closes.
server.on(‘checkContinue’, function (request, response) { }); // Emitted each time a request with an http Expect: 100-continue is received.
server.on(‘connect’, function (request, socket, head) { }); // Emitted each time a client requests a http CONNECT method.
server.on(‘upgrade’, function (request, socket, head) { }); // Emitted each time a client requests a http upgrade.
server.on(‘clientError’, function (exception, socket) { }); // If a client connection emits an ‘error’ event – it will forwarded here.
request.write(chunk, [encoding]); // Sends a chunk of the body.
request.end([data], [encoding]); // Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream.
request.abort(); // Aborts a request.
request.setTimeout(timeout, [callback]); // Once a socket is assigned to this request and is connected socket.setTimeout() will be called.
request.setNoDelay([noDelay]); // Once a socket is assigned to this request and is connected socket.setNoDelay() will be called.
request.setSocketKeepAlive([enable], [initialDelay]); // Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called.
request.on(‘response’, function(response) { }); // Emitted when a response is received to this request. This event is emitted only once.
request.on(‘socket’, function(socket) { }); // Emitted after a socket is assigned to this request.
request.on(‘connect’, function(response, socket, head) { }); // Emitted each time a server responds to a request with a CONNECT method. If this event isn’t being listened for, clients receiving a CONNECT method will have their connections closed.
request.on(‘upgrade’, function(response, socket, head) { }); // Emitted each time a server responds to a request with an upgrade. If this event isn’t being listened for, clients receiving an upgrade header will have their connections closed.
request.on(‘continue’, function() { }); // Emitted when the server sends a ‘100 Continue’ HTTP response, usually because the request contained ‘Expect: 100-continue’. This is an instruction that the client should send the request body.
response.write(chunk, [encoding]); // This sends a chunk of the response body. If this merthod is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.
response.writeContinue(); // Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent.
response.writeHead(statusCode, [reasonPhrase], [headers]); // Sends a response header to the request.
response.setTimeout(msecs, callback); // Sets the Socket’s timeout value to msecs. If a callback is provided, then it is added as a listener on the ‘timeout’ event on the response object.
response.setHeader(name, value); // Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.
response.getHeader(name); // Reads out a header that’s already been queued but not sent to the client. Note that the name is case insensitive.
response.removeHeader(name); // Removes a header that’s queued for implicit sending.
response.addTrailers(headers); // This method adds HTTP trailing headers (a header but at the end of the message) to the response.
response.end([data], [encoding]); // This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.
response.statusCode; // When using implicit headers (not calling response.writeHead() explicitly), this property controls the status code that will be sent to the client when the headers get flushed.
response.headersSent; // Boolean (read-only). True if headers were sent, false otherwise.
response.sendDate; // When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.
response.on(‘close’, function () { }); // Indicates that the underlying connection was terminated before response.end() was called or able to flush.
response.on(‘finish’, function() { }); // Emitted when the response has been sent.
message.httpVersion; // In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server.
message.headers; // The request/response headers object.
message.trailers; // The request/response trailers object. Only populated after the ‘end’ event.
message.method; // The request method as a string. Read only. Example: ‘GET’, ‘DELETE’.
message.url; // Request URL string. This contains only the URL that is present in the actual HTTP request.
message.statusCode; // The 3-digit HTTP response status code. E.G. 404.
message.socket; // The net.Socket object associated with the connection.
message.setTimeout(msecs, callback); // Calls message.connection.setTimeout(msecs, callback).
/* *******************************************************************************************
* URL
* http://nodejs.org/api/url.html
* ******************************************************************************************* */
// This module has utilities for URL resolution and parsing. Call require(‘url’) to use it.
url.parse(urlStr, [parseQueryString], [slashesDenoteHost]); // Take a URL string, and return an object.
url.format(urlObj); // Take a parsed URL object, and return a formatted URL string.
url.resolve(from, to); // Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.
/* *******************************************************************************************
* QUERY STRING
* http://nodejs.org/api/querystring.html
* ******************************************************************************************* */
// This module provides utilities for dealing with query strings. Call require(‘querystring’) to use it.
querystring.stringify(obj, [sep], [eq]); // Serialize an object to a query string. Optionally override the default separator (‘&’) and assignment (‘=’) characters.
querystring.parse(str, [sep], [eq], [options]); // Deserialize a query string to an object. Optionally override the default separator (‘&’) and assignment (‘=’) characters.
/* *******************************************************************************************
* ASSERT
* http://nodejs.org/api/assert.html
* ******************************************************************************************* */
// This module is used for writing unit tests for your applications, you can access it with require(‘assert’).
assert.fail(actual, expected, message, operator); // Throws an exception that displays the values for actual and expected separated by the provided operator.
assert(value, message); assert.ok(value, [message]); // Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);
assert.equal(actual, expected, [message]); // Tests shallow, coercive equality with the equal comparison operator ( == ).
assert.notEqual(actual, expected, [message]); // Tests shallow, coercive non-equality with the not equal comparison operator ( != ).
assert.deepEqual(actual, expected, [message]); // Tests for deep equality.
assert.notDeepEqual(actual, expected, [message]); // Tests for any deep inequality.
assert.strictEqual(actual, expected, [message]); // Tests strict equality, as determined by the strict equality operator ( === )
assert.notStrictEqual(actual, expected, [message]); // Tests strict non-equality, as determined by the strict not equal operator ( !== )
assert.throws(block, [error], [message]); // Expects block to throw an error. error can be constructor, RegExp or validation function.
assert.doesNotThrow(block, [message]); // Expects block not to throw an error, see assert.throws for details.
assert.ifError(value); // Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.
/* *******************************************************************************************
* OS
* http://nodejs.org/api/os.html
* ******************************************************************************************* */
// Provides a few basic operating-system related utility functions.
// Use require(‘os’) to access this module.
os.tmpdir(); // Returns the operating system’s default directory for temp files.
os.endianness(); // Returns the endianness of the CPU. Possible values are “BE” or “LE”.
os.hostname(); // Returns the hostname of the operating system.
os.type(); // Returns the operating system name.
os.platform(); // Returns the operating system platform.
os.arch(); // Returns the operating system CPU architecture.
os.release(); // Returns the operating system release.
os.uptime(); // Returns the system uptime in seconds.
os.loadavg(); // Returns an array containing the 1, 5, and 15 minute load averages.
os.totalmem(); // Returns the total amount of system memory in bytes.
os.freemem(); // Returns the amount of free system memory in bytes.
os.cpus(); // Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of milliseconds the CPU/core spent in: user, nice, sys, idle, and irq).
os.networkInterfaces(); // Get a list of network interfaces.
os.EOL; // A constant defining the appropriate End-of-line marker for the operating system.
/* *******************************************************************************************
* BUFFER
* http://nodejs.org/api/buffer.html
* ******************************************************************************************* */
// Buffer is used to dealing with binary data
// Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap
Buffer.from(size); // Allocates a new buffer of size octets.
Buffer.from(array); // Allocates a new buffer using an array of octets.
Buffer.from(str, [encoding]); // Allocates a new buffer containing the given str. encoding defaults to ‘utf8’.
Buffer.isEncoding(encoding); // Returns true if the encoding is a valid encoding argument, or false otherwise.
Buffer.isBuffer(obj); // Tests if obj is a Buffer
Buffer.concat(list, [totalLength]); // Returns a buffer which is the result of concatenating all the buffers in the list together.
Buffer.byteLength(string, [encoding]); // Gives the actual byte length of a string.
buf.write(string, [offset], [length], [encoding]); // Writes string to the buffer at offset using the given encoding
buf.toString([encoding], [start], [end]); // Decodes and returns a string from buffer data encoded with encoding (defaults to ‘utf8’) beginning at start (defaults to 0) and ending at end (defaults to buffer.length).
buf.toJSON(); // Returns a JSON-representation of the Buffer instance, which is identical to the output for JSON Arrays
buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd]); // Does copy between buffers. The source and target regions can be overlapped
buf.slice([start], [end]); // Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer.
buf.fill(value, [offset], [end]); // Fills the buffer with the specified value
buf[index]; // Get and set the octet at index
buf.length; // The size of the buffer in bytes, Note that this is not necessarily the size of the contents
buffer.INSPECT_MAX_BYTES; // How many bytes will be returned when buffer.inspect() is called. This can be overridden by user modules.
/* *******************************************************************************************
* GLOBAL OBJECTS > OBJECT
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
* ******************************************************************************************* */
// Global object: properties
Object.length // length is a property of a function object, and indicates how many arguments the function expects, i.e. the number of formal parameters. This number does not include the rest parameter. Has a value of 1.
Object.prototype // Represents the Object prototype object and allows to add new properties and methods to all objects of type Object.
// Methods of the Object constructor
Object.assign(target, …sources) // Copies the values of all enumerable own properties from one or more source objects to a target object. method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object
Object.create(MyObject) // Creates a new object with the specified prototype object and properties. The object which should be the prototype of the newly-created object.
Object.defineProperty(obj, prop, descriptor) // Adds the named property described by a given descriptor to an object.
Object.defineProperties(obj, props) // Adds the named properties described by the given descriptors to an object.
Object.entries(obj) // Returns an array containing all of the [key, value] pairs of a given object’s own enumerable string properties.
Object.freeze(obj) // Freezes an object: other code can’t delete or change any properties.
Object.getOwnPropertyDescriptor(obj, prop) // Returns a property descriptor for a named property on an object.
Object.getOwnPropertyDescriptors(obj) // Returns an object containing all own property descriptors for an object.
Object.getOwnPropertyNames(obj) // Returns an array containing the names of all of the given object’s own enumerable and non-enumerable properties.
Object.getOwnPropertySymbols(obj) // Returns an array of all symbol properties found directly upon a given object.
Object.getPrototypeOf(obj) // Returns the prototype of the specified object.
Object.is(value1, value2); // Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).
Object.isExtensible(obj) // Determines if extending of an object is allowed.
Object.isFrozen(obj) // Determines if an object was frozen.
Object.isSealed(obj) // Determines if an object is sealed.
Object.keys(obj) // Returns an array containing the names of all of the given object’s own enumerable string properties.
Object.preventExtensions(obj) // Prevents any extensions of an object.
Object.seal(obj) // Prevents other code from deleting properties of an object.
Object.setPrototypeOf(obj, prototype) // Sets the prototype (i.e., the internal [[Prototype]] property).
Object.values(obj) // Returns an array containing the values that correspond to all of a given object’s own enumerable string properties.
// Object instances and Object prototype object (Object.prototype.property or Object.prototype.method())
// Properties
obj.constructor // Specifies the function that creates an object’s prototype.
obj.__proto__ // Points to the object which was used as prototype when the object was instantiated.
// Methods
obj.hasOwnProperty(prop) // Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.
prototypeObj.isPrototypeOf(object) // Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.
obj.propertyIsEnumerable(prop) // Returns a boolean indicating if the internal ECMAScript [[Enumerable]] attribute is set.
obj.toLocaleString() // Calls toString().
obj.toString() // Returns a string representation of the object.
object.valueOf() // Returns the primitive value of the specified object.
/* *******************************************************************************************
* GLOBAL OBJECTS > ARRAY
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
* ******************************************************************************************* */
// Global object: properties
Array.length // Reflects the number of elements in an array.
Array.prototype // Represents the prototype for the Array constructor and allows to add new properties and methods to all Array objects.
// Global object: methods
Array.from(arrayLike[, mapFn[, thisArg]]) // Creates a new Array instance from an array-like or iterable object.
Array.isArray(obj) // Returns true if a variable is an array, if not false.
Array.of(element0[, element1[, …[, elementN]]]) // Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
// Instance: properties
arr.length // Reflects the number of elements in an array.
// Instance: mutator methods
arr.copyWithin(target, start, end) // Copies a sequence of array elements within the array.
arr.fill(value, start, end) // Fills all the elements of an array from a start index to an end index with a static value.
arr.pop() // Removes the last element from an array and returns that element.
arr.push([element1[, …[, elementN]]]) // Adds one or more elements to the end of an array and returns the new length of the array.
arr.reverse() // Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first.
arr.shift() // Removes the first element from an array and returns that element.
arr.sort() // Sorts the elements of an array in place and returns the array.
array.splice(start, deleteCount, item1, item2, …) // Adds and/or removes elements from an array.
arr.unshift([element1[, …[, elementN]]]) // Adds one or more elements to the front of an array and returns the new length of the array.
// Instance: accessor methods
arr.concat(value1[, value2[, …[, valueN]]]) // Returns a new array comprised of this array joined with other array(s) and/or value(s).
arr.includes(searchElement, fromIndex) // Determines whether an array contains a certain element, returning true or false as appropriate.
arr.indexOf(searchElement[, fromIndex]) // Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
arr.join(separator) // Joins all elements of an array into a string.
arr.lastIndexOf(searchElement, fromIndex) // Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
arr.slice(begin, end) // Extracts a section of an array and returns a new array.
arr.toString() // Returns a string representing the array and its elements. Overrides the Object.prototype.toString() method.
arr.toLocaleString(locales, options) // Returns a localized string representing the array and its elements. Overrides the Object.prototype.toLocaleString() method.
// Instance: iteration methods
arr.entries() // Returns a new Array Iterator object that contains the key/value pairs for each index in the array.
arr.every(callback[, thisArg]) // Returns true if every element in this array satisfies the provided testing function.
arr.filter(callback[, thisArg]) // Creates a new array with all of the elements of this array for which the provided filtering function returns true.
arr.find(callback[, thisArg]) // Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found.
arr.findIndex(callback[, thisArg]) // Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found.
arr.forEach(callback[, thisArg]) // Calls a function for each element in the array.
arr.keys() // Returns a new Array Iterator that contains the keys for each index in the array.
arr.map(callback[, initialValue]) // Creates a new array with the results of calling a provided function on every element in this array.
arr.reduce(callback[, initialValue]) // Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
arr.reduceRight(callback[, initialValue]) // Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.
arr.some(callback[, initialValue]) // Returns true if at least one element in this array satisfies the provided testing function.
arr.values() // Returns a new Array Iterator object that contains the values for each index in the array.
A large collection of Javascript related ebooks and also some frameworks
JavaScript
- Basic JavaScript for the impatient programmer – Dr. Axel Rauschmayer
- Book of Modern Frontend Tooling
- Crockford’s JavaScript – Douglas Crockford
- Dev Docs
- Developing Backbone.js Applications – Addy Osmani
- Directory of free Javascript ebooks
- Eloquent JavaScript 2nd edition – Marijn Haverbeke
- Exploring ES6 – Dr. Axel Rauschmayer
- Google JavaScript Style Guide
- Human JavaScript
- JavaScript Allongé – Reginald Braithwaite
- JavaScript Bible (PDF)
- JavaScript Challenges Book
- JavaScript Enlightenment – Cody Lindley
- JavaScript ES6 and beyond – Alberto Montalesi (PDF, epub)
- JavaScript For Cats
- JavaScript Fundamentals, Plus a Dash Of JQuery – for dinner ladies
- JavaScript Garden (Maintained by Tim Ruffles)
- JavaScript Patterns Collection – Shi Chuan
- JavaScript Spessore – Reginald Braithwaite
- Javascript Succinctly, Syncfusion (PDF, Kindle) (email address requested, not required)
- JavaScript the Right Way
- jQuery Fundamentals (starts with JavaScript basics)
- JS Robots (PDF)
- Leaflet Tips and Tricks: Interactive Maps Made Easy – Malcolm Maclean
- Learn to Code JavaScript by Playing a Game
- Learning JavaScript Design Patterns – Addy Osmani
- Let’s Learn ES6 – Ryan Christiani (Superbook format)
- Managing Space and Time with JavaScript – Book 1: The Basics – Noel Rappin
- Marionette Exposé: Learn to write modular Javascript applications using Backbone Marionette and RequireJS/AMD – Jack Killilea (Leanpub account or valid email requested)
- Mastering JavaScript High Performance – Chad R. Adams, Packt. (email address requested, not required)
- Mozilla Developer Network’s JavaScript Guide
- O’Reilly Programming JavaScript Applications
- Object-Oriented JavaScript – Stoyan Stefanov, Kumar Chetan Sharma (email address requested, not required)
- Oh My JS – Azat Mardanov
- Patterns For Large-Scale JavaScript Application Architecture – Addy Osmani
- Speaking JavaScript – Dr. Axel Rauschmayer
- The JavaScript Tutorial
- The JavaScript Way – Baptiste Pesquet
- The Problem with Native JavaScript APIs
- Thinking in JavaScript – Aravind Shenoy, Packt. (email address requested, not required)
- Understanding ECMAScript 6 – Nicholas C. Zakas
- Understanding JavaScript OOP (Sorella)
- You Don’t Know JS
Angular.js
- Angular for the jQuery developer
- Angular.js Guide
- Angular.js Material Designing
- Angular.js Tutorial
- AngularJS – Step by Logical Step
- AngularJS Essentials – Rodrigo Branas, Packt (email address requested, not required)
- AngularJS Succinctly (PDF, Kindle) (email address requested, not required)
- AngularJs vs EmberJs
- AngularJS with Ruby on Rails
- Developing with Angular – Denys Vuika (Leanpub account or valid email requested)
- Recipes with Angular.js – Frederik Dietz
- Seven-Part Introduction to Angular
- Unit Testing Best Practices in AngularJS
Aurelia
- Beginning Aurelia – behzad (Leanpub account or valid email requested)
Backbone.js
- A Complete guide for learning Backbone.js
- A pragmatic guide to Backbone.js apps
- Backbone Tutorials: Beginner, Intermediate and Advanced – Thomas Davis (Leanpub account or valid email requested)
- Backbone.js + Require.js, Modularization and Just in Time Dependency Loading, part 1 part 2
- Backbone.js and socket.io
- Backbonejs Tutorials
- Building Single Page Web Apps with Backbone.js (🚧 in process)
- Developing Backbone.js Applications
- Getting Started with Backbone.js
- How to share Backbone.js models with node.js
Booty5.js
D3.js
- D3 Tips and Tricks – Malcolm Maclean
- Dashing D3.js Tutorial
- Interactive Data Visualization for the Web
- Interactive Data Visualization with D3
Dojo
- Dojo: The Definitive Guide – Matthew A. Russell
Elm
- An Introduction to Elm (HTML)
- Beginning Elm – Pawan Poudel (HTML)
- Building a Live-Validating Signup Form in Elm
- Elm Accelerated – James Porter
- Elm Programming Language (HTML)
- Elm Tutorial
- Learn You an Elm (HTML)
- The Elm Architecture
Ember.js
- AngularJs vs EmberJs
- DockYard Ember.js Style Guide
- Ember App with RailsApi
- Ember.js – Getting started
- Vic Ramon’s Ember Tutorial
Express.js
- Express.js Guide – Azat Mardanov
jQuery
- JavaScript Fundamentals, Plus a Dash Of JQuery – for dinner ladies
- jQuery Novice to Ninja (PDF)
- jQuery Succinctly, Syncfusion (PDF, Kindle) (email address requested, not required)
Meteor
- BulletProof Meteor
- Your First Meteor Application, A Complete Beginner’s Guide to the Meteor JavaScript Framework
Node.js
- An Introduction to libuv – Nikhil Marathe (PDF – ePub)
- Mixu’s Node Book
- Node Documentation
- Node: Up and Running – Tom Hughes-Croucher
- Node.js Succinctly, Syncfusion (PDF, Kindle) (email address requested, not required)
- The Node Beginner Book
- What You Need To Know About Node.js – Bruno Joseph Dmello, Packt (email address requested, not required)
Om
React
- Free React on Rails course
- Hacking with React
- Intro to the React Framework
- Learning React.js: Getting Started and Concepts
- React-Bits (vasanthk)
- React Enlightenment
- React In-depth: An exploration of UI development
- React Primer Draft
- React Tutorial
- React Tutorial by Josh Finnie
- React with ASP.NET Core Tutorial
- React.js Tutorial: Now is Your Time to Try It, Right in Your Browser
- SurviveJS – Webpack and React
- The Road to learn React – Build a Hacker News App along the Way – Robin Wieruch (Leanpub account or valid email requested) markdown
React Native
- Programming React Native (Leanpub account or valid email requested)
- React Native Animation Book
- React Native Express
- React Native Training
Redux
- Full-Stack Redux Tutorial
- SoundCloud Application in React + Redux
- The Complete Redux Book – Boris Dinkevich and Ilya Gelman (Leanpub account or valid email requested)