Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Learn Node.js_ Introduction to Node.js Cheatsheet _ Codecademy

Learn Bash Scripting_ Bash Scripting Cheatsheet _ Codecademy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Learn Node.js_ Introduction to Node.js Cheatsheet _ Codecademy

Learn Bash Scripting_ Bash Scripting Cheatsheet _ Codecademy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Cheatsheets / Learn Node.

js

Introduction to Node.js
Node.js REPL
Node.js comes with REPL, an abbreviation for read–eval–print loop. REPL
contains three di erent states: //node is typed in the console to access REPL
*a read state where it reads the input from a user, *the eval state where it $ node
evaluates the user’s input *the print state where it prints out the evaluation to
the console. //the > indicates that REPL is running
After these states are nished REPL loops through these states repeatedly. REPL
// anything written after > will be evaluated
is useful as it gives back immediate feedback which can be used to perform
> console.log("HI")
calculations and develop code.

// REPL has evaluated the line and has printed out HI


HI

Node.js Global Object


The Node.js environment has a global object that contains every Node-speci c
global property. The global object can be accessed by either typing in //Two ways to access global
console.log(global) or global in the terminal after RPL is running. In order to > console.log(global)
see just the keys Object.keys(global) can be used. Since global is an object, //or
new properties can be assigned to it via global.name_of_property = > global
'value_of_property' .

//Adding new property to global


> global.car = 'delorean'
Node.js Process Object
A process is the instance of a computer program that is being executed. Node
has a global process object with useful properties. One of these properties is if (process.env.NODE_ENV === 'development'){
NODE_ENV which can be used in an if/else statement to perform di erent tasks console.log('Do not deploy!! Do not deploy!!');
depending on if the application is in the production or development phase. }

Node.js process.argv
process.argv is a property that holds an array of command-line values provided
when the current process was initiated. The rst element in the array is the node web.js testing several features
absolute path to the Node, followed by the path to the le that’s running and console.log(process.argv[2])// 'features' will be printed
nally any command-line arguments provided when the process was initiated.

Node.js process.memoryUsage()
process.memoryUsage() is a method that can be used to return information on
the CPU demands of the current process. Heap can refer to a speci c data //using process.memoryUsage() will return an object in
structure or to the computer memory. a format like this:

{ rss: 26247168,
heapTotal: 5767168,
heapUsed: 3573032,
external: 8772 }

Node.js Modules
In Node.js les are called modules. Modularity is a technique where one program
has distinct parts each providing a single piece of the overall functionality - like let baseball = require(./babeRuth.js)
pieces of a puzzle coming together to complete a picture. require() is a
function used to bring one module into another.
Node.js Core Modules
Node has several modules included within the environment to e ciently
perform common tasks. These are known as the core modules. The core let http = require('http');
modules are de ned within Node.js’s source and are located in the lib/ folder.
A core module can be accessed by passing a string with the name of the module
into the require() function.

Node.js Local Modules


In Node.js les are considered modules. Modules that are created locally are
called local modules. These local modules are held in an object called module . // type.js
This object has a property called exports which allows a module to be // by using the export property we can use this module in
accessed in a di erent module. another file
module.exports = class key {
constructor(car) {
this.car = car;
}
};

// qwerty.js
// by requiring the type.js file we can we use the module
in the type.js file
let Dog = require('./type.js');

Node Package Manager


NPM stands for node-package-manager. An NPM is essentially a collection of
code from other developers that we can use. When Node is installed the npm
command-line tool is downloaded as well. This command-line tool enables us to
interact with the registry via our terminal.
EventEmitter Class
Node.js has an EventEmitter class which can be accessed by requiring the
events core module. Each event emitter instance has an .on() method which // Require in the 'events' core module
assigns a listener callback function to a named event. EventEmitter also has an let events = require('events');
.emit() method which announces a named event that has occurred.

// Create an instance of the EventEmitter class


let myEmitter = new events.EventEmitter();
let version = (data) => {
console.log(`participant: ${data}.`);
};

// Assign the version function as the listener callback


for 'new user' events
myEmitter.on('new user', version)

// Emit a 'new user' event


myEmitter.emit('new user', 'Lily Pad')
// 'Lily Pad'

Asynchronous Node.js
Node.js is a non-blocking, asynchronous environment. The event loop in Node.js
enables asynchronous actions to be handled in a non-blocking way. Node.js let endgame = () => {
provides APIs which allow operations to be put in a queue, waiting to be console.log('I am inevitable')
executed after the previous operation nishes. If synchronous tasks never end, };
operations waiting in the event-queue will never execute.

// endgame will run after 1000ms


setTimeout(endgame, 1000);
Asynchronous Error Handling
The Node environment has all the standard JavaScript errors as well as the
JavaScript Error class for creating new error instances. Many asynchronous
Node APIs use error- rst callback functions: callback functions which have an
error as the rst expected argument and the data as the second argument. If the
asynchronous task results in an error, it will be passed in as the rst argument to
the callback function. If no error was thrown, the rst argument will be
undefined .

Node.js Input/Output
Input is data that is given to the computer, while output is any data or feedback
that a computer provides. In Node, we can get input from a user by using the // Recieves an input
stdin.on() method on the process object. We are able to use this because process.stdin.on();
.on() is an instance of EventEmitter. To give an output we can use the
.stdout.write() method on the process object as well. This is because
// Gives an output
console.log() is a thin wrapper on .stdout.write() .
process.stdout.write();

Filesystem
A lesystem is how you access and organize all data on a computer. The Node.js
fs core module is an API for interacting with the le system. Each method // First argument is the file path
available through the fs module has a synchronous version and an // The second argument is the file’s character encoding
asynchronous version. One of the methods in the fs core module is the // The third argument is the invoked function
.readfile() method which allows us to read data from a le. fs.readFile('./file.txt', 'utf-8', CallbackFunction);

Web Server
Node was designed with back end development needs as a top priority. One of
these needs is the ability to create web servers. A web server is a computer const http = require('http');
process that listens for requests from clients and returns responses. A Node
core module designed to meet these needs is the http module. This module has
functions that simplify receiving and responding to requests.
Creating A Server
http.createServer() is a method that returns an instance of an http.server .
The method .listen() in http.server tells the server to “listen” for incoming // required in the http core module.
connections. We give http.createServer() a callback function also known as the const http = require('http');
requestListener , which will be triggered once the server is listening and
receives a request. The requestlistener requests a request object and a
let requestListener = (request, response) => {
response object.
// code to be filled in depending on server
};

// assigning return value


const server = http.createServer(requestListener);

// assigning server port


server.listen(3000);

Readable/Writable Streams
In most cases, data isn’t processed all at once but rather piece by piece. This is
what we call streams. Streaming data is preferred as it doesn’t require tons of // Readable stream
RAM and doesn’t need to have all the data on hand to begin processing it. To readline.createInterface();
read les line-by-line, we can use the .createInterface() method from the
readline core module. We can write to streams by using the
// Writtable Stream
.createWriteStream() method.
fs.createWriteStream();

You might also like