Day 22, Node.js

Horray, Node.js is finally upon us.

The spring was mostly fun and Hao was a great pair. We got stunk on one tiny problem for a couple of hours, but everything went very smoothly. The tiny problem was that we ended our HTTP response outside of the callback function that deals with HTTP requests. The original intention was to reuse code, and the real consequence was our server ends the response before firing the callback. Welcome to the world of async, and we definitely learned the lesson the hard way.

Async:

– Code runs out of order with other code or control flow.

– Code runs in a future time point because either it takes a long time to finish running or it waits for events in the future. For example, file system IO or networking

Events:

– A special kind of async. All event-driven systems are async, but the opposite is not true.

– For example,

req.on('data', function(){});
//mostly for server handling POST request
//req is available as soon as the request header is received, (hint: before the data is received)
req.on('end', function(){});

Modularity:

– Good for the coder and good for the code.

– One of this sprint’s focus.

– Easier because of Node.js’s exports and require system

Other tips:

– The prime tester toy problem. Very first optimization should be only dividing up to Math.sqrt(number_to_be_tested).

– Node.js’s require and exports.


var my_module = require('./my_module.js');

//my_module is a obj

Inside my_module.js:

exports.func_one = function(){};

//magic line to be inserted by the system in the end of my_module.js

//return exports

– Something that reloads node.js code for you: nodemon (not nodemom, hehe). We used and it worked as advertised.

Cookies:

– Key-value pairs tied to the domain

– It is NOT stored inside the local storage and its size is limited to 4kb

– Cookies are likely to be available after the browser is closed

We also covered different ways of doing cross origin requests.

Advertisements
Standard