node Flashcards
debug commands
- cont = continue
- next = step over the next statement
- step = step into next statement
- out = step out of the current executing funtion
- backtrace = show me the current call execution frame or call stack
- repl = start the node REPL to allow me to view variables and execute code
- watch(expr) = add the given expression to the watch list
- list(n) = list the n lines of source code before and after the currently stopped line.
- node-inspector is a browser based debugger that this author likes
Some string functions
>“wishy washy winter”.indexOf(“wash”);
6
>“No, they’re saying Booo-urns.”.substr(19, 3);
‘Boo’
>“No, they’re saying Booo-urns.”.slice(19, 22);
‘Boo’
> ‘ cat \n\n\n ‘.trim();
‘cat’
some regex examples
> “aaooo”.replace(new RegExp(“[Aa]{2,}”), “b”);
‘boo’
> “aaooo”.replace(/[Aa]{2,0}/, “b”);
‘boo’
search works the same and returns the index at which the regex starts.
array operations
- Array.isArray(arr); // V8 JS only
- arr.length // duh
- arr.push(‘arr entry’); is the same as: arr[arr.length] = ‘arr entry’;
- delete arr[2] gets rid of the element at position two, but leaves the position there.
- splice gets rid of the element. arr.splice(2,2) returns two items from the array starting at the second position. arr now doesn’t have those items
- arr.unshift(1); adds 1 to the beginning
- arr.shift(); returns and removes the first item
- join and sort do what you’d expect
- arr.forEach(function(val) {…};
Type comparison and conversion
> “” == false == null == undefined == 0
true
> null === undefined
false
// object constructors can get tricky
> var x = 234;
> var x1 = new Number(234);
> typeof x1;
‘object’
> x1 == x;
true
> x1 === x;
false
functions
name anonymous functions, better for debugging
all functions have an internal object called ‘arguments’.
Language constructs
> var pet = animal_meows ? “cat” : “dog”;
// numbers are double precision floating points, but bitwise operations are supproted
&, | , ~, ^
these first convert operands to 32 bit ints
perform bitwise comparison
return number back to js number
while, do…while, and for loops exist
also for…in loop (in V8 JS)
for ( key in user) {
do stuff
}
Classes
no explicit class keyword or type
classes are declared as functions
function Shape() {
this. X = 0;
this. Y = 0;
this. move = function(x,y){
this. X = x;
this. Y = y;
}
this.distance_from_origin = function(){
return Math.sqrt(this.X*this.X + this.Y*this.Y);
}
}
etc.
Add properties and methods to an instantiated class all you want.
s = new Shape(14,24);
s.FillColour = ‘red’;
prototypes and inheritance
all objects have a prototype. it is the mechanism by which they inherit properties and methods
instanceof is helpful in comparing instances
function Shape() {
}
Shape.prototype.X = 0;
Shape.prototype.Y = 0;
Shape.prototype.move = function(x,y) {
//move stuff
}
Shape.prototype.distance_from_origin = function(){
//dist calcs
}
Shape.prototype.area = function(){
throw new Error(“no shape yet”)
}
var s = new Shape();
s. move(19,19)
s. distance_from_origin();
function Square () {
}
Square.prototype = new Shape();
Square.prototype.__proto__ = Shape.prototype;
Square.prototype.Width = 0;
Square.prototype.area = function(){
//etc…
};
… you get it.
Node.js Globals
global - like the browser’s “window”, it’s available everywhere. attach stuff to it.
console methods:
log(msg)
warn(msg)
time(label)
timeEnd(label) // prints time between starting ‘label’ time
assert(cond, message)
process methods:
lots of stuff to be dealt with later
exit
env
cwd
What is node good at?
common network application tasks.
Heavy I/O and requests to other services.
Not good at expensive calculations and computations.
When doing computationally intensive stuff, relinquish control of execution now and then to do other stuff with nextTick method on the process global
process.nextTick(sub_function_that_does_your_thing);
Writing Modules
- Create folder to hold module contents
- create file called package.json in this folder. Should contain at least a name for the module and a “main”: main_mod.js javascript file that node should load initially for the module
- if node doesn’t find package.json or a main js file, it looks for index.js (or index.node)
ex. photo manager example from book:
create directory “album_mgr”. Place in it “lib/” and “test/” subdirectories. create package.json file with contents:
{ “name”: “album-manager”, “version”: “1.0.0”, “main”: “./lib/albums.js” }
Also include a Readme.md file. Learn some markdown.
JS code will now look a lot like the example, but it returns an object called “exports”. So all functions/attributes will be attached to exports
exports. version = “1.0.0”;
exports. albums = function (root, callback) {
..
}
async.waterfall
asyc.series
figure 5.1
about location 2673
waterfall
- takes an array of functions and executes them one at a time, passing results from each function to the next.
- At the end, a resulting function is called with the results from the final function in the array.
series
- results from one function are not passed to next
- Instead, each functon passes it’s results to an array, one entry per function.
- the final function gets this array as its second argument (after “err”).
- functions can be in an array or an object.
- In the case of the object, the results are an object with same keys as the functions called.
async.parallel
async.auto
approximate loc 2794
parallel
- like series, accepts array or object of functions
- executes them simultaneously, passing them to results and the final function
auto
- accepts object in which keys represent functions or an array of dependencies then a function to execute once those deps are met
async. auto({numbers: function(cb){…},
strings: function(cb) {…},
assemble: [‘numbers’, ‘strings’,
function(cb, thus_far ) {…}]
},
//optional final function
function (err, results){ do stuff w/ results});
Looping asynchronously
loc 2827
this replaces that unweildy recursive iterator in the book.
async.forEachSeries(arr,
function(element, callback) {
// do stuff with element
callback(null); // must call for each element
},
function (err) {
if (err) { etc. }
});
this waits for each element to finish before going to the next.
async.forEach does all at once. asyn waits for them all to finish.