node Flashcards

1
Q

debug commands

A
  1. cont = continue
  2. next = step over the next statement
  3. step = step into next statement
  4. out = step out of the current executing funtion
  5. backtrace = show me the current call execution frame or call stack
  6. repl = start the node REPL to allow me to view variables and execute code
  7. watch(expr) = add the given expression to the watch list
  8. list(n) = list the n lines of source code before and after the currently stopped line.
  9. node-inspector is a browser based debugger that this author likes
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Some string functions

A

>“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’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

some regex examples

A

> “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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

array operations

A
  1. Array.isArray(arr); // V8 JS only
  2. arr.length // duh
  3. arr.push(‘arr entry’); is the same as: arr[arr.length] = ‘arr entry’;
  4. delete arr[2] gets rid of the element at position two, but leaves the position there.
  5. 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
  6. arr.unshift(1); adds 1 to the beginning
  7. arr.shift(); returns and removes the first item
  8. join and sort do what you’d expect
  9. arr.forEach(function(val) {…};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Type comparison and conversion

A

> “” == 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

functions

A

name anonymous functions, better for debugging

all functions have an internal object called ‘arguments’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Language constructs

A

> 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

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Classes

A

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’;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

prototypes and inheritance

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Node.js Globals

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is node good at?

A

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);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Writing Modules

A
  1. Create folder to hold module contents
  2. 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
  3. 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) {

..

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

async.waterfall

asyc.series

figure 5.1

about location 2673

A

waterfall

  1. takes an array of functions and executes them one at a time, passing results from each function to the next.
  2. At the end, a resulting function is called with the results from the final function in the array.

series

  1. results from one function are not passed to next
  2. Instead, each functon passes it’s results to an array, one entry per function.
  3. the final function gets this array as its second argument (after “err”).
  4. functions can be in an array or an object.
  5. In the case of the object, the results are an object with same keys as the functions called.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

async.parallel

async.auto

approximate loc 2794

A

parallel

  1. like series, accepts array or object of functions
  2. executes them simultaneously, passing them to results and the final function

auto

  1. 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});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Looping asynchronously

loc 2827

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Reading a file

should be able to recite this code.

A
var fs = require('fs');
 var contents;

var rs = fs.createReadStream(“06simple_stream.js”);

rs.on('readable', function () {
 var str;
 var d = rs.read();
 if (d) {
   if (typeof d == 'string') {
    str = d;
   } else if (typeof d == 'object' && d instanceof Buffer ) {
    str = d.toString('utf8');
   }
   if (str) {
    if (!contents)
     contents = d;
    else
     contents += str;
   }
 }
 });

rs.on(‘end’, function () {
console.log(‘read in the file contents: ‘);
console.log(contents.toString(‘utf8’));
});

prose

create a stream from a file

wait for something to be there, listening to ‘readable’ with “on” method on the stream.

read the stream to a variable

if it’s a string pass it to another variable.

If it’s a buffer, read it to another variable.

finally, pass it to a variable made outside the “on” method.

listen to ‘end’ and do the thing you need to.

17
Q

Buffers

A

var b = new Buffer(10000);

var str = ‘some text’;

b. write(str);
console. log( b.length ); // prints 10,000

You must keep track of what you’ve written to a buffer.