Skip to content
This repository has been archived by the owner on Apr 8, 2019. It is now read-only.

3.4 Refactor startup process

zoe-1 edited this page Mar 29, 2015 · 2 revisions

Refactor init() and make start.js.

Export init() from ./lib/index.js and make ./start.js to invoke the init().
Configure package.json to execute the start.js script.
start.js should invoke init() to use port 8000 and a callback that outputs
the server details to console when started.
This file is not covered in tests.

In respect to init():
The method should accept a port and a callback.
The callback should execute if there are errors or not.
The callback will always have two parameters passed to it:
1. err
2. server.
Sample exports.init()

Error Handling and the callback().

Different scripts are going to execute the init().
In this assignment start.js and test scripts are going to use/consume it.

So, if there is an error when executing the init() different scripts
may handle the error in different ways. This is why we pass the error state back up the callback chain. In other words, we pass error state as a parameter to the callback().

When writing error handling code either you pass the error up the call back chain
or just make the application shutdown. Passing errors up the callback chain makes
your errors "throw safe" and does not asplode the person's application when your module
does not work.

This is important when writing plugins that other people will use.
Imagine that you are using a plugin developed by someone else and it throws an error
and shuts your whole application down because it failed when you called it. If it just
passed the error state back up the callback() chain to you, then you could decide if you
want to shut the application down or not etc. ect.....

Above observation was based on discussion with @TheAlphaNerd for this assignment.
To see this concept in action look at his:
init(),
start.js
./test/index.js
Observe how start.js and ./test/index.js all use the init().
However, they handle the error state differently.

server object and the callback().

The callback() in the init() also receives a server object as the second parameter.
This is important because it allows tests to stop and restart the server.

Refactor below scripts

./lib/index.js
./start.js
package.json
   npm start -- should now execute node start.js.

At the end of this section you should be able to run your server
using the start.js script. The next section will cover building tests.

Sample Projects to Look At:

@TheAlphaNerd Assignment3
@Chyld Assignment3
@idanwe Assignment3
@zoe-1 Assignment3

Next Testing with lab and code