├── .gitignore
├── .travis.yml
├── README.md
├── ex-01-hello
├── app.js
└── package.json
├── ex-02-fs-read
├── app.js
├── hello.txt
└── package.json
├── ex-03-fs-read-promise
├── app.js
├── hello.txt
└── package.json
├── ex-04-fs-read-co
├── app.js
├── hello.txt
└── package.json
├── ex-05-fs-read-koa
├── app.js
├── hello.txt
└── package.json
├── ex-06-koa-next
├── app.js
└── package.json
├── ex-07-querystring
├── app.js
└── package.json
├── ex-08-express-qs
├── app.js
└── package.json
├── ex-09-koa-qs
├── app.js
└── package.json
├── ex-10-routing
├── app.js
└── package.json
├── ex-11-express-routing
├── app.js
└── package.json
├── ex-12-koa-routing
├── app.js
└── package.json
├── ex-13-fs-write-promise
├── .gitignore
├── app.js
└── package.json
├── ex-14-server-client
├── client.js
├── package.json
└── server.js
├── ex-15-express-request
├── client.js
├── package.json
└── server.js
├── ex-16-mocha
├── math.js
├── package.json
└── test
│ └── test.js
├── ex-17-mocha-chai-should
├── math.js
├── package.json
└── test
│ └── test.js
├── ex-18-mocha-chai-expect
├── math.js
├── package.json
└── test
│ └── test.js
├── ex-19-express-bodyparser
├── app.js
└── package.json
├── ex-20-koa-bodyparser
├── app.js
└── package.json
├── ex-21-express-supertest
├── app.js
├── package.json
└── test
│ └── test.js
├── ex-22-koa-supertest
├── app.js
├── package.json
└── test
│ └── test.js
├── ex-23-express-static
├── app.js
├── package.json
└── public
│ ├── github-octocat.png
│ ├── hello.css
│ ├── hello.html
│ └── hello.js
├── ex-24-koa-static
├── app.js
├── package.json
└── public
│ ├── github-octocat.png
│ ├── hello.css
│ ├── hello.html
│ └── hello.js
├── ex-25-express-session
├── app.js
└── package.json
├── ex-26-koa-session
├── app.js
└── package.json
├── ex-27-express-formidable
├── app.js
├── package.json
└── upload
│ └── .gitignore
├── ex-28-koa-formidable
├── app.js
├── package.json
└── upload
│ └── .gitignore
├── ex-29-express-multi-router
├── app.js
└── package.json
├── ex-30-koa-multi-router
├── app.js
└── package.json
├── ex-31-fs-read-koa-async-await
├── README.md
├── app.js
├── hello.txt
├── package.json
└── run.js
├── ex-32-password
├── .gitignore
├── app.js
└── package.json
├── ex-33-password-bcrypt
├── .gitignore
├── app.js
└── package.json
├── ex-34-debug
├── README.md
├── a.js
├── b.js
├── c.js
├── main.js
└── package.json
├── ex-35-uuid-cuid-lodash.uniqueId
├── app.js
└── package.json
├── ex-36-superagent-cheerio
├── app.js
└── package.json
├── ex-37-minimist
├── README.md
├── bin
│ └── program.js
└── package.json
├── ex-38-commander
├── README.md
├── bin
│ └── program.js
└── package.json
├── ex-39-inquirer
├── bin
│ └── program.js
└── package.json
├── ex-40-password-bcrypt-bson
├── .gitignore
├── app.js
└── package.json
├── ex-41-image-resize-gm
├── README.md
├── bin
│ └── resize.js
├── image
│ └── github-octocat.png
├── output
│ └── .gitignore
└── package.json
├── ex-42-bluebird
├── all.js
├── any.js
├── cancel.js
├── package.json
├── promise.js
├── promisify.js
├── some.js
├── spread.js
└── timeout.js
├── ex-43-express-render-jade
├── app.js
├── package.json
└── views
│ └── index.jade
├── ex-44-koa-render-jade
├── app.js
├── package.json
└── views
│ └── index.jade
├── ex-45-csv
├── app.js
└── package.json
├── ex-46-markdown-marked
├── app.js
└── package.json
├── ex-47-xml2js
├── app.js
├── package.json
└── sample.xml
├── ex-48-glob
├── aaa.js
├── app.js
├── bbb.js
├── ccc.js
├── examples
│ ├── a.js
│ ├── b.js
│ ├── c.js
│ ├── tim.css
│ ├── tim.html
│ └── tim.js
├── package.json
└── tim.min.js
├── ex-49-mkdirp-del-rimraf-touch
├── README.md
├── create.js
├── delete.js
├── example
│ └── .gitignore
├── mkdir-p.js
├── package.json
└── rm-rf.js
├── ex-50-express-query-body-param
├── README.md
├── app.js
└── package.json
├── ex-51-koa-query-body-param
├── README.md
├── app.js
└── package.json
├── ex-52-node_env-nconf
├── app-nconf.js
├── app.js
├── config.json
└── package.json
├── ex-53-validator
├── app.js
└── package.json
├── ex-54-express-csrf
├── app.js
└── package.json
├── ex-55-koa-csrf
├── app.js
└── package.json
├── ex-56-express-gzip
├── app.js
└── package.json
├── ex-57-koa-gzip
├── app.js
└── package.json
├── ex-58-http-socket.io
├── app.js
├── boom.jpg
├── index.html
├── index.js
└── package.json
├── ex-59-express-socket.io
├── app.js
├── boom.jpg
├── index.html
├── index.js
└── package.json
├── ex-60-koa-socket.io
├── app.js
├── boom.jpg
├── index.html
├── index.js
└── package.json
├── ex-61-jsdom
├── app.js
└── package.json
├── ex-62-virtual-dom
├── app.js
└── package.json
├── ex-63-phantomjs
├── .gitignore
├── README.md
├── app.js
└── package.json
├── ex-64-nightmare
├── package.json
└── test.js
├── ex-65-proxyquire
├── a.js
├── b.js
├── package.json
└── test.js
├── ex-66-istanbul
├── .gitignore
├── math.js
├── package.json
└── test
│ └── test.js
├── ex-67-travis-ci
├── README.md
├── math.js
└── test
│ └── test.js
├── ex-68-sinon
├── a.txt
├── fake-timer.js
├── fs-proxy.js
├── once.js
├── package.json
├── random-throw.js
├── random.js
├── test
│ ├── spy.js
│ └── stub.js
└── try.js
├── ex-69-coveralls
└── README.md
├── ex-70-mocha-nightmare
├── package.json
└── test.js
├── ex-71-node-blocked
├── app.js
└── package.json
├── ex-72-esprima
├── app.js
└── package.json
├── ex-73-simple-peer
├── app.js
└── package.json
├── ex-74-consolidate
├── ejs.js
├── haml.js
├── handlebars.js
├── jade.js
├── lodash.js
├── mustache.js
├── nunjucks.js
├── package.json
├── react.js
├── swig.js
└── views
│ ├── app.react.js
│ ├── index.ejs
│ ├── index.haml
│ ├── index.hbs
│ ├── index.html
│ ├── index.jade
│ ├── index.lodash
│ ├── index.mustache
│ └── index.swig
├── ex-75-d3-to-png
├── .gitignore
├── README.md
├── app.js
└── package.json
├── ex-76-nodemailer-mailgun
├── .gitignore
├── README.md
├── app.js
└── package.json
├── ex-77-benchmark
├── app.js
└── package.json
├── ex-78-redis
├── 2-clients.js
├── app.js
└── package.json
├── ex-79-umd
├── .gitignore
├── README.md
├── app.js
└── subapp.js
├── ex-80-promise-to-native
├── bluebird.js
├── es6.js
└── package.json
├── ex-81-event-emitter
├── app.js
└── package.json
├── ex-82-build-express-middleeare
├── app.js
├── package.json
├── req-decorator.js
└── res-decorator.js
├── ex-83-build-koa-middleeare
├── app.js
├── package.json
├── req-decorator.js
└── res-decorator.js
├── ex-84-exec-bash
├── app.js
└── package.json
├── ex-85-process-fork
├── app.js
├── package.json
└── worker.js
├── ex-86-levelup
├── .gitignore
├── app.js
└── package.json
├── ex-87-rethinkdb
├── .gitignore
├── README.md
├── app.js
└── package.json
├── ex-88-email-template
├── .gitignore
├── README.md
├── app.js
├── package.json
└── templates
│ └── newsletter
│ ├── html.jade
│ ├── style.stylus
│ └── text.jade
├── ex-89-json-server
├── README.md
├── db.json
└── package.json
├── ex-90-dns
├── app.js
└── package.json
├── exercises
├── coo.js
├── hello.txt
├── koaa.js
├── promisee.js
└── server.js
├── exx-01-electron
├── README.md
├── index.html
├── main.js
└── package.json
├── exx-02-ajax
├── index.html
├── index.js
├── main.js
└── package.json
├── exx-03-d3
├── index.html
├── index.js
├── main.js
└── package.json
├── exx-04-cool-face
├── index.html
├── index.js
├── main.js
└── package.json
└── package.json
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 |
3 | npm-debug.log
4 |
5 | .DS_Store
6 |
7 | # Code coverage
8 | coverage
9 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "0.10"
4 | - "0.11"
5 | - "0.12"
6 | - "iojs"
7 | script: "npm run test-travis"
8 | after_script: "npm install coveralls@2 && cat ./coverage/lcov.info | coveralls"
9 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # startLearningNodejs
2 |
3 | [![Build Status][travis-image]][travis-url]
4 | [![Test coverage][coveralls-image]][coveralls-url]
5 |
6 | It is for practicing node.js
7 |
8 | - ex-01: node http server hello world
9 | - ex-02: node http server + fs read
10 | - ex-03: node http server + fs read (promise)
11 | - ex-04: node http server + fs read (co + promise)
12 | - ex-05: koa server + fs read (promise)
13 | - ex-06: koa next middleware
14 | - ex-07: node parse querystring
15 | - ex-08: express get queries
16 | - ex-09: koa get queries
17 | - ex-10: node server routing
18 | - ex-11: express routing
19 | - ex-12: koa routing (koa-router)
20 | - ex-13: node http server + fs write (promise)
21 | - ex-14: http server with http client
22 | - ex-15: express with request
23 | - ex-16: mocha (assert)
24 | - ex-17: mocha + chai (should)
25 | - ex-18: mocha + chai (expect)
26 | - ex-19: express body parser
27 | - ex-20: koa body parser
28 | - ex-21: express supertest
29 | - ex-22: koa supertest
30 | - ex-23: express static server
31 | - ex-24: koa static server
32 | - ex-25: express session
33 | - ex-26: koa session
34 | - ex-27: express file upload (formidable)
35 | - ex-28: koa file upload (formidable)
36 | - ex-29: express multi-router
37 | - ex-30: koa multi-router
38 | - ex-31: koa server (async-await) + fs read (promise)
39 | - ex-32: express server + plain text password
40 | - ex-33: express server + bcrypt password hash
41 | - ex-34: debug
42 | - ex-35: uuid + cuid + lodash.uniqueId
43 | - ex-36: web parser (superagent + cheerio)
44 | - ex-37: command line program (minimist)
45 | - ex-38: command line program (commander)
46 | - ex-39: command line program (inquirer)
47 | - ex-40: express server + bcrypt password hash + bson
48 | - ex-41: image resize (gm with GraphicsMagick)
49 | - ex-42: promise usage (bluebird)
50 | - ex-43: express render jade
51 | - ex-44: koa render jade (koa-views)
52 | - ex-45: csv
53 | - ex-46: markdown (marked)
54 | - ex-47: xml2js
55 | - ex-48: glob
56 | - ex-49: touch + del + mkdirp + rimraf
57 | - ex-50: express query vs body vs param
58 | - ex-51: koa query vs body vs param
59 | - ex-52: NODE_ENV & nconf
60 | - ex-53: validator
61 | - ex-54: express csrf (csurf)
62 | - ex-55: koa csrf (koa-csrf)
63 | - ex-56: express gzip (compression)
64 | - ex-57: koa gzip (koa-compress)
65 | - ex-58: http socket.io
66 | - ex-59: express socket.io
67 | - ex-60: koa socket.io
68 | - ex-61: node dom (jsdom)
69 | - ex-62: virtual dom
70 | - ex-63: phantomjs
71 | - ex-64: nightmare
72 | - ex-65: stub (proxyquire)
73 | - ex-66: code coverage (istanbul)
74 | - ex-67: continuous integration (travis-ci)
75 | - ex-68: spy + stub + fake timer (sinon)
76 | - ex-69: code coverage integration (coveralls)
77 | - ex-70: mocha-nightmare
78 | - ex-71: node-blocked
79 | - ex-72: esprima
80 | - ex-73: simple-peer
81 | - ex-74: template (consolidate)
82 | - ex-75: d3-to-png
83 | - ex-76: nodemailer (mailgun)
84 | - ex-77: benchmark
85 | - ex-78: redis
86 | - ex-79: umd (browserify)
87 | - ex-80: promise to native
88 | - ex-81: event-emitter
89 | - ex-82: build express middleware
90 | - ex-83: build koa middleware
91 | - ex-84: execute bash
92 | - ex-85: process fork
93 | - ex-86: levelup
94 | - ex-87: rethinkdb
95 | - ex-88: email-template (jade + stylus)
96 | - ex-89: json-server
97 | - ex-90: dns resolve
98 |
99 |
100 | - exx-01: electron hello world
101 | - exx-02: github user display (superagent + cheerio)
102 | - exx-03: d3
103 | - exx-04: cool-face
104 |
105 | [travis-image]: https://travis-ci.org/Chiara-yen/startLearningNodejs.svg
106 | [travis-url]: https://travis-ci.org/Chiara-yen/startLearningNodejs
107 | [coveralls-image]: https://img.shields.io/coveralls/Chiara-yen/startLearningNodejs.svg?style=flat-square
108 | [coveralls-url]: https://coveralls.io/r/Chiara-yen/startLearningNodejs
109 |
--------------------------------------------------------------------------------
/ex-01-hello/app.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 |
3 |
4 | http.createServer(function(request, response) {
5 | response.writeHead(200, {'Content-Type':'text/plain'});
6 | response.write('Hello');
7 | response.end();
8 | }).listen(3000);
9 |
--------------------------------------------------------------------------------
/ex-01-hello/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-01-hello",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC"
12 | }
13 |
--------------------------------------------------------------------------------
/ex-02-fs-read/app.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 | var fs = require('fs');
3 |
4 |
5 | http.createServer(function(request, response) {
6 | response.writeHead(200, {'Content-Type':'text/plain'});
7 |
8 | fs.readFile(__dirname + '/hello.txt', function(err, text) {
9 | response.write(text);
10 | response.end();
11 | });
12 |
13 | }).listen(3000);
14 |
--------------------------------------------------------------------------------
/ex-02-fs-read/hello.txt:
--------------------------------------------------------------------------------
1 | Hello World!
2 |
--------------------------------------------------------------------------------
/ex-02-fs-read/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-02-fs-read",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC"
12 | }
13 |
--------------------------------------------------------------------------------
/ex-03-fs-read-promise/app.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 | var Promise = require('bluebird');
3 | var readFile = Promise.promisify(require('fs').readFile);
4 |
5 |
6 | http.createServer(function(request, response) {
7 | response.writeHead(200, {'Content-Type':'text/plain'});
8 |
9 | readFile(__dirname + '/hello.txt')
10 | .then(function(text) {
11 | response.write(text);
12 | response.end();
13 | });
14 |
15 | }).listen(3000);
16 |
17 |
18 | /*
19 | new Promise(function(resolve, reject) {});
20 | Promise.a = function(){...};
21 | */
22 |
--------------------------------------------------------------------------------
/ex-03-fs-read-promise/hello.txt:
--------------------------------------------------------------------------------
1 | Hello World!
2 |
--------------------------------------------------------------------------------
/ex-03-fs-read-promise/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-03-fs-read-promise",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bluebird": "^2.9.25"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-04-fs-read-co/app.js:
--------------------------------------------------------------------------------
1 | var co = require('co');
2 | var http = require('http');
3 | var Promise = require('bluebird');
4 | var readFile = Promise.promisify(require('fs').readFile);
5 |
6 |
7 | http.createServer(function(request, response) {
8 |
9 | co(function *() {
10 | response.writeHead(200, {'Content-Type':'text/plain'});
11 | var text = yield readFile(__dirname + '/hello.txt');
12 | response.write(text + ' Tim!');
13 | response.end();
14 | });
15 |
16 | }).listen(3000);
17 |
18 |
19 |
20 | /* ES7
21 | async function *() {
22 | var text = await readFile(__dirname + '/hello.txt');
23 | response.write(text);
24 | response.end();
25 | }
26 | */
27 |
--------------------------------------------------------------------------------
/ex-04-fs-read-co/hello.txt:
--------------------------------------------------------------------------------
1 | Hello World!
2 |
--------------------------------------------------------------------------------
/ex-04-fs-read-co/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-04-fs-read-co",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bluebird": "^2.9.25",
14 | "co": "^4.5.2"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-05-fs-read-koa/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var app = koa();
3 | var Promise = require('bluebird');
4 | var readFile = Promise.promisify(require('fs').readFile);
5 |
6 |
7 | // file is a Buffer
8 | app.use(function *() {
9 | var file = yield readFile(__dirname + '/hello.txt');
10 | this.body = file.toString();
11 | });
12 |
13 | app.listen(3000);
14 |
--------------------------------------------------------------------------------
/ex-05-fs-read-koa/hello.txt:
--------------------------------------------------------------------------------
1 | Hello World!
2 |
--------------------------------------------------------------------------------
/ex-05-fs-read-koa/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-05-fs-read-koa",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bluebird": "^2.9.25",
14 | "koa": "^0.19.1"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-06-koa-next/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var app = koa();
3 |
4 |
5 | app.use(function *(next) {
6 | this.body = ' 1!';
7 | yield next;
8 | this.body += ' 5!';
9 | });
10 |
11 | app.use(function *(next) {
12 | this.body += ' 2!';
13 | try {
14 | yield next;
15 | } catch (e) {
16 | this.body += ' 4!';
17 | }
18 |
19 | });
20 |
21 | app.use(function *() {
22 | throw new Error('boooom');
23 | this.body += ' 3!';
24 | });
25 |
26 |
27 | app.listen(3000);
28 |
--------------------------------------------------------------------------------
/ex-06-koa-next/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-06-koa-next",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "koa": "^0.19.1"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-07-querystring/app.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 | var qs = require('querystring');
3 |
4 | http.createServer(function(request, response) {
5 | var url = request.url;
6 | var parts = url.split('?');
7 | var str = parts[1] || '';
8 | var query = qs.parse(str);
9 | response.write(JSON.stringify(query));
10 | response.end();
11 | }).listen(3000);
12 |
--------------------------------------------------------------------------------
/ex-07-querystring/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-07-querystring",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC"
12 | }
13 |
--------------------------------------------------------------------------------
/ex-08-express-qs/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var app = express();
3 |
4 |
5 | app.use(function(req, res) {
6 | res.json(req.query);
7 | });
8 |
9 |
10 | app.listen(3000);
11 |
--------------------------------------------------------------------------------
/ex-08-express-qs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-08-express-qs",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.12.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-09-koa-qs/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var app = koa();
3 |
4 |
5 | app.use(function *() {
6 | this.body = this.request.query;
7 | });
8 |
9 | app.listen(3000);
10 |
--------------------------------------------------------------------------------
/ex-09-koa-qs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-09-koa-qs",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "koa": "^0.19.1"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-10-routing/app.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 |
3 |
4 | http.createServer(function(request, response) {
5 |
6 | var url = request.url;
7 | var parts = url.split('?');
8 | var path = parts[0] || '';
9 |
10 | if (path === '/') {
11 | response.writeHead(200, {'Content-Type':'text/plain'});
12 | response.write('Home');
13 | } else if (path === '/tim') {
14 | response.writeHead(200, {'Content-Type':'text/plain'});
15 | response.write('Tim');
16 | } else if (path === '/roth') {
17 | response.writeHead(200, {'Content-Type':'text/plain'});
18 | response.write('Roth');
19 | } else {
20 | response.writeHead(404);
21 | response.write('Page Not Found');
22 | }
23 |
24 | response.end();
25 |
26 | }).listen(3000);
27 |
--------------------------------------------------------------------------------
/ex-10-routing/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-10-routing",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC"
12 | }
13 |
--------------------------------------------------------------------------------
/ex-11-express-routing/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var app = express();
3 |
4 | var router = express.Router();
5 |
6 |
7 | router.get('/', function(req, res) {
8 | res.send('Home');
9 | });
10 |
11 | router.get('/tim', function(req, res) {
12 | res.send('Tim');
13 | });
14 |
15 | router.get('/roth', function(req, res) {
16 | res.send('Roth');
17 | });
18 |
19 | app.use('/', router);
20 |
21 | app.use(function(req, res) {
22 | res.sendStatus(404);
23 | });
24 |
25 | app.listen(3000);
26 |
--------------------------------------------------------------------------------
/ex-11-express-routing/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-11-express-routing",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.12.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-12-koa-routing/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var router = require('koa-router')();
3 | var app = koa();
4 |
5 |
6 |
7 | router.get('/', function *() {
8 | this.body = 'Home';
9 | });
10 |
11 | router.get('/tim', function *() {
12 | this.body = 'Tim';
13 | });
14 |
15 | router.get('/roth', function *() {
16 | this.body = 'Roth';
17 | });
18 |
19 | app.use(function *(next) {
20 | yield next;
21 | // Handle 404 upstream.
22 | var status = this.status || 404;
23 | if (status === 404) this.body = 'Page Not Found';
24 | });
25 |
26 | app.use(router.routes());
27 |
28 |
29 | app.listen(3000);
30 |
--------------------------------------------------------------------------------
/ex-12-koa-routing/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-12-koa-routing",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "koa": "^0.19.1",
14 | "koa-router": "^4.3.2"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-13-fs-write-promise/.gitignore:
--------------------------------------------------------------------------------
1 | hello.txt
2 |
--------------------------------------------------------------------------------
/ex-13-fs-write-promise/app.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 | var Promise = require('bluebird');
3 | var writeFile = Promise.promisify(require('fs').writeFile);
4 |
5 |
6 | http.createServer(function(request, response) {
7 |
8 | var url = request.url;
9 | var parts = url.split('?');
10 | var str = parts[1] || '';
11 |
12 | response.writeHead(200, {'Content-Type':'text/plain'});
13 |
14 | writeFile(__dirname + '/hello.txt', str)
15 | .then(function() {
16 | response.write('success');
17 | response.end();
18 | });
19 |
20 | }).listen(3000);
21 |
22 |
23 | /*
24 | new Promise(function(resolve, reject) {});
25 | Promise.a = function(){...};
26 | */
27 |
--------------------------------------------------------------------------------
/ex-13-fs-write-promise/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-13-fs-write-promise",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bluebird": "^2.9.25"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-14-server-client/client.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 |
3 | http.get('http://localhost:3000/', function(res) {
4 | res.on('data', function (chunk) {
5 | console.log(chunk.toString());
6 | });
7 | });
8 |
--------------------------------------------------------------------------------
/ex-14-server-client/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-14-server-client",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "client.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "node server.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bluebird": "^2.9.25"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-14-server-client/server.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 |
3 |
4 | http.createServer(function(request, response) {
5 | response.writeHead(200, {'Content-Type':'text/plain'});
6 | response.write('Hello');
7 | response.end();
8 | }).listen(3000);
9 |
--------------------------------------------------------------------------------
/ex-15-express-request/client.js:
--------------------------------------------------------------------------------
1 | var request = require('request');
2 |
3 | request('http://localhost:3000/', function (err, response, body) {
4 | if (!err && response.statusCode === 200) {
5 | console.log(body);
6 | }
7 | });
8 |
--------------------------------------------------------------------------------
/ex-15-express-request/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-15-express-request",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "client.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "node server.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.12.3",
14 | "request": "^2.55.0"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-15-express-request/server.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var app = express();
3 |
4 |
5 | app.use(function(req, res) {
6 | res.send('Hello');
7 | });
8 |
9 |
10 | app.listen(3000);
11 |
--------------------------------------------------------------------------------
/ex-16-mocha/math.js:
--------------------------------------------------------------------------------
1 | var math = module.exports = {};
2 |
3 | math.add = function(a, b) {
4 | throwWhenNotNumber(a);
5 | throwWhenNotNumber(b);
6 | return a + b;
7 | };
8 |
9 |
10 | math.subtract = function(a, b) {
11 | throwWhenNotNumber(a);
12 | throwWhenNotNumber(b);
13 | return a - b;
14 | };
15 |
16 |
17 | math.multiply = function(a, b) {
18 | throwWhenNotNumber(a);
19 | throwWhenNotNumber(b);
20 | return a * b;
21 | };
22 |
23 |
24 | math.divide = function(a, b) {
25 | throwWhenNotNumber(a);
26 | throwWhenNotNumber(b);
27 | throwWhenZero(b);
28 | return a / b;
29 | };
30 |
31 |
32 | function throwWhenNotNumber(num) {
33 | if (typeof num !== 'number') {
34 | throw new TypeError(num + ' is not a number');
35 | }
36 | }
37 |
38 | function throwWhenZero(num) {
39 | if (num === 0) {
40 | throw new Error('cant not be 0');
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/ex-16-mocha/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-16-mocha",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "directories": {
7 | "test": "test"
8 | },
9 | "scripts": {
10 | "test": "mocha"
11 | },
12 | "author": "",
13 | "license": "ISC",
14 | "devDependencies": {
15 | "mocha": "^2.2.4"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ex-16-mocha/test/test.js:
--------------------------------------------------------------------------------
1 | var assert = require('assert');
2 | var math = require('../math');
3 |
4 | describe('add', function () {
5 | it('should throw when first argument not number', function() {
6 | try {
7 | math.add('a', 1);
8 | } catch (e) {
9 | assert('a is not a number' === e.message);
10 | }
11 | });
12 |
13 | it('should throw when second argument not number', function() {
14 | try {
15 | math.add(1, 'b');
16 | } catch (e) {
17 | assert('b is not a number' === e.message);
18 | }
19 | });
20 |
21 | it('should work with positive', function() {
22 | var result = math.add(1, 2);
23 | assert(3 === result);
24 | });
25 |
26 | it('should work with 0', function() {
27 | var result = math.add(0, 0);
28 | assert(0 === result);
29 | });
30 |
31 | it('should work with negative', function() {
32 | var result = math.add(-1, -2);
33 | assert(-3 === result);
34 | });
35 | });
36 |
37 |
38 | describe('subtract', function () {
39 | it('should throw when first argument not number', function() {
40 | try {
41 | math.subtract('a', 1);
42 | } catch (e) {
43 | assert('a is not a number' === e.message);
44 | }
45 | });
46 |
47 | it('should throw when second argument not number', function() {
48 | try {
49 | math.subtract(1, 'b');
50 | } catch (e) {
51 | assert('b is not a number' === e.message);
52 | }
53 | });
54 |
55 | it('should work with positive', function() {
56 | var result = math.subtract(5, 2);
57 | assert(3 === result);
58 | });
59 |
60 | it('should work with 0', function() {
61 | var result = math.subtract(0, 0);
62 | assert(0 === result);
63 | });
64 |
65 | it('should work with negative', function() {
66 | var result = math.subtract(-1, -2);
67 | assert(1 === result);
68 | });
69 | });
70 |
71 | describe('multiply', function () {
72 | it('should throw when first argument not number', function() {
73 | try {
74 | math.multiply('a', 1);
75 | } catch (e) {
76 | assert('a is not a number' === e.message);
77 | }
78 | });
79 |
80 | it('should throw when second argument not number', function() {
81 | try {
82 | math.multiply(1, 'b');
83 | } catch (e) {
84 | assert('b is not a number' === e.message);
85 | }
86 | });
87 |
88 | it('should work with positive', function() {
89 | var result = math.multiply(5, 2);
90 | assert(10 === result);
91 | });
92 |
93 | it('should work with 0', function() {
94 | var result = math.multiply(5, 0);
95 | assert(0 === result);
96 | });
97 |
98 | it('should work with negative', function() {
99 | var result = math.multiply(-1, -2);
100 | assert(2 === result);
101 | });
102 | });
103 |
104 | describe('divide', function () {
105 | it('should throw when first argument not number', function() {
106 | try {
107 | math.divide('a', 1);
108 | } catch (e) {
109 | assert('a is not a number' === e.message);
110 | }
111 | });
112 |
113 | it('should throw when second argument not number', function() {
114 | try {
115 | math.divide(1, 'b');
116 | } catch (e) {
117 | assert('b is not a number' === e.message);
118 | }
119 | });
120 |
121 | it('should throw when divide by 0', function() {
122 | try {
123 | math.divide(5, 0);
124 | } catch (e) {
125 | assert('cant not be 0' === e.message);
126 | }
127 | });
128 |
129 | it('should work with positive', function() {
130 | var result = math.divide(5, 2);
131 | assert(5/2 === result);
132 | });
133 |
134 | it('should work with negative', function() {
135 | var result = math.divide(-1, -2);
136 | assert(1/2 === result);
137 | });
138 | });
139 |
--------------------------------------------------------------------------------
/ex-17-mocha-chai-should/math.js:
--------------------------------------------------------------------------------
1 | var math = module.exports = {};
2 |
3 | math.add = function(a, b) {
4 | throwWhenNotNumber(a);
5 | throwWhenNotNumber(b);
6 | return a + b;
7 | };
8 |
9 |
10 | math.subtract = function(a, b) {
11 | throwWhenNotNumber(a);
12 | throwWhenNotNumber(b);
13 | return a - b;
14 | };
15 |
16 |
17 | math.multiply = function(a, b) {
18 | throwWhenNotNumber(a);
19 | throwWhenNotNumber(b);
20 | return a * b;
21 | };
22 |
23 |
24 | math.divide = function(a, b) {
25 | throwWhenNotNumber(a);
26 | throwWhenNotNumber(b);
27 | throwWhenZero(b);
28 | return a / b;
29 | };
30 |
31 |
32 | function throwWhenNotNumber(num) {
33 | if (typeof num !== 'number') {
34 | throw new TypeError(num + ' is not a number');
35 | }
36 | }
37 |
38 | function throwWhenZero(num) {
39 | if (num === 0) {
40 | throw new Error('cant not be 0');
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/ex-17-mocha-chai-should/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-17-mocha-chai-should",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "mocha"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "devDependencies": {
12 | "chai": "^2.3.0",
13 | "mocha": "^2.2.4"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-17-mocha-chai-should/test/test.js:
--------------------------------------------------------------------------------
1 | require('chai').should();
2 | var math = require('../math');
3 |
4 | describe('add', function () {
5 | it('should throw when first argument not number', function() {
6 | try {
7 | math.add('a', 1);
8 | } catch (e) {
9 | e.message.should.be.equal('a is not a number');
10 | }
11 | });
12 |
13 | it('should throw when second argument not number', function() {
14 | try {
15 | math.add(1, 'b');
16 | } catch (e) {
17 | e.message.should.be.equal('b is not a number');
18 | }
19 | });
20 |
21 | it('should work with positive', function() {
22 | var result = math.add(1, 2);
23 | result.should.be.equal(3);
24 | });
25 |
26 | it('should work with 0', function() {
27 | var result = math.add(0, 0);
28 | result.should.be.equal(0);
29 | });
30 |
31 | it('should work with negative', function() {
32 | var result = math.add(-1, -2);
33 | result.should.be.equal(-3);
34 | });
35 | });
36 |
37 |
38 | describe('subtract', function () {
39 | it('should throw when first argument not number', function() {
40 | try {
41 | math.subtract('a', 1);
42 | } catch (e) {
43 | e.message.should.be.equal('a is not a number');
44 | }
45 | });
46 |
47 | it('should throw when second argument not number', function() {
48 | try {
49 | math.subtract(1, 'b');
50 | } catch (e) {
51 | e.message.should.be.equal('b is not a number');
52 | }
53 | });
54 |
55 | it('should work with positive', function() {
56 | var result = math.subtract(5, 2);
57 | result.should.be.equal(3);
58 | });
59 |
60 | it('should work with 0', function() {
61 | var result = math.subtract(0, 0);
62 | result.should.be.equal(0);
63 | });
64 |
65 | it('should work with negative', function() {
66 | var result = math.subtract(-1, -2);
67 | result.should.be.equal(1);
68 | });
69 | });
70 |
71 | describe('multiply', function () {
72 | it('should throw when first argument not number', function() {
73 | try {
74 | math.multiply('a', 1);
75 | } catch (e) {
76 | e.message.should.be.equal('a is not a number');
77 | }
78 | });
79 |
80 | it('should throw when second argument not number', function() {
81 | try {
82 | math.multiply(1, 'b');
83 | } catch (e) {
84 | e.message.should.be.equal('b is not a number');
85 | }
86 | });
87 |
88 | it('should work with positive', function() {
89 | var result = math.multiply(5, 2);
90 | result.should.be.equal(10);
91 | });
92 |
93 | it('should work with 0', function() {
94 | var result = math.multiply(5, 0);
95 | result.should.be.equal(0);
96 | });
97 |
98 | it('should work with negative', function() {
99 | var result = math.multiply(-1, -2);
100 | result.should.be.equal(2);
101 | });
102 | });
103 |
104 | describe('divide', function () {
105 | it('should throw when first argument not number', function() {
106 | try {
107 | math.divide('a', 1);
108 | } catch (e) {
109 | e.message.should.be.equal('a is not a number');
110 | }
111 | });
112 |
113 | it('should throw when second argument not number', function() {
114 | try {
115 | math.divide(1, 'b');
116 | } catch (e) {
117 | e.message.should.be.equal('b is not a number');
118 | }
119 | });
120 |
121 | it('should throw when divide by 0', function() {
122 | try {
123 | math.divide(5, 0);
124 | } catch (e) {
125 | e.message.should.be.equal('cant not be 0');
126 | }
127 | });
128 |
129 | it('should work with positive', function() {
130 | var result = math.divide(5, 2);
131 | result.should.be.equal(5/2);
132 | });
133 |
134 | it('should work with negative', function() {
135 | var result = math.divide(-1, -2);
136 | result.should.be.equal(1/2);
137 | });
138 | });
139 |
--------------------------------------------------------------------------------
/ex-18-mocha-chai-expect/math.js:
--------------------------------------------------------------------------------
1 | var math = module.exports = {};
2 |
3 | math.add = function(a, b) {
4 | throwWhenNotNumber(a);
5 | throwWhenNotNumber(b);
6 | return a + b;
7 | };
8 |
9 |
10 | math.subtract = function(a, b) {
11 | throwWhenNotNumber(a);
12 | throwWhenNotNumber(b);
13 | return a - b;
14 | };
15 |
16 |
17 | math.multiply = function(a, b) {
18 | throwWhenNotNumber(a);
19 | throwWhenNotNumber(b);
20 | return a * b;
21 | };
22 |
23 |
24 | math.divide = function(a, b) {
25 | throwWhenNotNumber(a);
26 | throwWhenNotNumber(b);
27 | throwWhenZero(b);
28 | return a / b;
29 | };
30 |
31 |
32 | function throwWhenNotNumber(num) {
33 | if (typeof num !== 'number') {
34 | throw new TypeError(num + ' is not a number');
35 | }
36 | }
37 |
38 | function throwWhenZero(num) {
39 | if (num === 0) {
40 | throw new Error('cant not be 0');
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/ex-18-mocha-chai-expect/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-18-mocha-chai-expect",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "mocha"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "devDependencies": {
12 | "chai": "^2.3.0",
13 | "mocha": "^2.2.4"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-18-mocha-chai-expect/test/test.js:
--------------------------------------------------------------------------------
1 | var expect = require('chai').expect;
2 | var math = require('../math');
3 |
4 | describe('add', function () {
5 | it('should throw when first argument not number', function() {
6 | try {
7 | math.add('a', 1);
8 | } catch (e) {
9 | expect(e.message).is.equal('a is not a number');
10 | }
11 | });
12 |
13 | it('should throw when second argument not number', function() {
14 | try {
15 | math.add(1, 'b');
16 | } catch (e) {
17 | expect(e.message).is.equal('b is not a number');
18 | }
19 | });
20 |
21 | it('should work with positive', function() {
22 | var result = math.add(1, 2);
23 | expect(result).is.equal(3);
24 | });
25 |
26 | it('should work with 0', function() {
27 | var result = math.add(0, 0);
28 | expect(result).is.equal(0);
29 | });
30 |
31 | it('should work with negative', function() {
32 | var result = math.add(-1, -2);
33 | expect(result).is.equal(-3);
34 | });
35 | });
36 |
37 |
38 | describe('subtract', function () {
39 | it('should throw when first argument not number', function() {
40 | try {
41 | math.subtract('a', 1);
42 | } catch (e) {
43 | expect(e.message).is.equal('a is not a number');
44 | }
45 | });
46 |
47 | it('should throw when second argument not number', function() {
48 | try {
49 | math.subtract(1, 'b');
50 | } catch (e) {
51 | expect(e.message).is.equal('b is not a number');
52 | }
53 | });
54 |
55 | it('should work with positive', function() {
56 | var result = math.subtract(5, 2);
57 | expect(result).is.equal(3);
58 | });
59 |
60 | it('should work with 0', function() {
61 | var result = math.subtract(0, 0);
62 | expect(result).is.equal(0);
63 | });
64 |
65 | it('should work with negative', function() {
66 | var result = math.subtract(-1, -2);
67 | expect(result).is.equal(1);
68 | });
69 | });
70 |
71 | describe('multiply', function () {
72 | it('should throw when first argument not number', function() {
73 | try {
74 | math.multiply('a', 1);
75 | } catch (e) {
76 | expect(e.message).is.equal('a is not a number');
77 | }
78 | });
79 |
80 | it('should throw when second argument not number', function() {
81 | try {
82 | math.multiply(1, 'b');
83 | } catch (e) {
84 | expect(e.message).is.equal('b is not a number');
85 | }
86 | });
87 |
88 | it('should work with positive', function() {
89 | var result = math.multiply(5, 2);
90 | expect(result).is.equal(10);
91 | });
92 |
93 | it('should work with 0', function() {
94 | var result = math.multiply(5, 0);
95 | expect(result).is.equal(0);
96 | });
97 |
98 | it('should work with negative', function() {
99 | var result = math.multiply(-1, -2);
100 | expect(result).is.equal(2);
101 | });
102 | });
103 |
104 | describe('divide', function () {
105 | it('should throw when first argument not number', function() {
106 | try {
107 | math.divide('a', 1);
108 | } catch (e) {
109 | expect(e.message).is.equal('a is not a number');
110 | }
111 | });
112 |
113 | it('should throw when second argument not number', function() {
114 | try {
115 | math.divide(1, 'b');
116 | } catch (e) {
117 | expect(e.message).is.equal('b is not a number');
118 | }
119 | });
120 |
121 | it('should throw when divide by 0', function() {
122 | try {
123 | math.divide(5, 0);
124 | } catch (e) {
125 | expect(e.message).is.equal('cant not be 0');
126 | }
127 | });
128 |
129 | it('should work with positive', function() {
130 | var result = math.divide(5, 2);
131 | expect(result).is.equal(5/2);
132 | });
133 |
134 | it('should work with negative', function() {
135 | var result = math.divide(-1, -2);
136 | expect(result).is.equal(1/2);
137 | });
138 | });
139 |
--------------------------------------------------------------------------------
/ex-19-express-bodyparser/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var bodyParser = require('body-parser');
3 | var app = express();
4 |
5 | app.use(bodyParser.urlencoded({ extended: false }));
6 | app.use(bodyParser.json());
7 |
8 | app.post('/', function(req, res) {
9 | res.send(JSON.stringify(req.body));
10 | });
11 |
12 | app.listen(3000);
13 |
--------------------------------------------------------------------------------
/ex-19-express-bodyparser/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-19-express-bodyparser",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "body-parser": "^1.12.3",
14 | "express": "^4.12.3"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-20-koa-bodyparser/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var bodyParser = require('koa-bodyparser');
3 | var app = koa();
4 |
5 | app.use(bodyParser());
6 |
7 | app.use(function *() {
8 | this.body = this.request.body;
9 | });
10 |
11 | app.listen(3000);
12 |
--------------------------------------------------------------------------------
/ex-20-koa-bodyparser/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-20-koa-bodyparser",
3 | "version": "1.0.0",
4 | "main": "app.js",
5 | "scripts": {
6 | "start": "node --harmony-generators app.js",
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "koa": "^0.19.1",
13 | "koa-bodyparser": "^1.5.0"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-21-express-supertest/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var bodyParser = require('body-parser');
3 | var app = express();
4 |
5 | app.use(bodyParser.urlencoded({ extended: false }));
6 | app.use(bodyParser.json());
7 |
8 | app.get('/', function(req, res) {
9 | res.json(req.query);
10 | });
11 |
12 | app.post('/', function(req, res) {
13 | res.json(req.body);
14 | });
15 |
16 | module.exports = app;
17 |
--------------------------------------------------------------------------------
/ex-21-express-supertest/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-21-express-supertest",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "test": "mocha"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "body-parser": "^1.12.3",
13 | "express": "^4.12.3"
14 | },
15 | "devDependencies": {
16 | "mocha": "^2.2.4",
17 | "supertest": "^0.15.0"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/ex-21-express-supertest/test/test.js:
--------------------------------------------------------------------------------
1 | var request = require('supertest');
2 | var app = require('../app');
3 |
4 | var FAKE = { name: 'Tim', species: 'cat' };
5 |
6 | describe('GET /', function() {
7 | it('will return queries', function(done) {
8 | request(app)
9 | .get('/')
10 | .query(FAKE)
11 | .expect('Content-Type', /json/)
12 | .expect(200)
13 | .expect(function(res) {
14 | if (!(res.body && res.body.name === FAKE.name && res.body.species === FAKE.species))
15 | return 'not response bodies';
16 | })
17 | .end(done);
18 | });
19 | });
20 |
21 |
22 | describe('POST /', function() {
23 | it('will return bodies', function(done) {
24 | request(app)
25 | .post('/')
26 | .send(FAKE)
27 | .expect('Content-Type', /json/)
28 | .expect(200)
29 | .expect(function(res) {
30 | if (!(res.body && res.body.name === FAKE.name && res.body.species === FAKE.species))
31 | return 'not response bodies';
32 | })
33 | .end(done);
34 | });
35 | });
36 |
--------------------------------------------------------------------------------
/ex-22-koa-supertest/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var bodyParser = require('koa-bodyparser');
3 | var router = require('koa-router')();
4 | var app = koa();
5 |
6 | app.use(bodyParser());
7 |
8 | router.get('/', function *() {
9 | this.body = this.request.query;
10 | });
11 |
12 | router.post('/', function *() {
13 | this.body = this.request.body;
14 | });
15 |
16 |
17 | app.use(function *(next) {
18 | yield next;
19 | // Handle 404 upstream.
20 | var status = this.status || 404;
21 | if (status === 404) this.body = 'Page Not Found';
22 | });
23 |
24 | app.use(router.routes());
25 |
26 | module.exports = app;
27 |
--------------------------------------------------------------------------------
/ex-22-koa-supertest/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-22-koa-supertest",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "directories": {
7 | "test": "test"
8 | },
9 | "scripts": {
10 | "test": "mocha --harmony"
11 | },
12 | "author": "",
13 | "license": "ISC",
14 | "devDependencies": {
15 | "mocha": "^2.2.4",
16 | "supertest": "^0.15.0"
17 | },
18 | "dependencies": {
19 | "koa": "^0.20.0",
20 | "koa-bodyparser": "^1.5.0",
21 | "koa-router": "^4.3.2"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/ex-22-koa-supertest/test/test.js:
--------------------------------------------------------------------------------
1 | var request = require('supertest');
2 | var app = require('../app');
3 |
4 | var FAKE = { name: 'Tim', species: 'cat' };
5 |
6 | describe('GET /', function() {
7 | it('will return queries', function(done) {
8 | request(app.listen())
9 | .get('/')
10 | .query(FAKE)
11 | .expect('Content-Type', /json/)
12 | .expect(200)
13 | .expect(function(res) {
14 | if (!(res.body && res.body.name === FAKE.name && res.body.species === FAKE.species))
15 | return 'not response bodies';
16 | })
17 | .end(done);
18 | });
19 | });
20 |
21 |
22 | describe('POST /', function() {
23 | it('will return bodies', function(done) {
24 | request(app.listen())
25 | .post('/')
26 | .send(FAKE)
27 | .expect('Content-Type', /json/)
28 | .expect(200)
29 | .expect(function(res) {
30 | if (!(res.body && res.body.name === FAKE.name && res.body.species === FAKE.species))
31 | return 'not response bodies';
32 | })
33 | .end(done);
34 | });
35 | });
36 |
--------------------------------------------------------------------------------
/ex-23-express-static/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var app = express();
3 |
4 |
5 | app.use(express.static('public'));
6 |
7 |
8 | app.listen(3000);
9 |
--------------------------------------------------------------------------------
/ex-23-express-static/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-23-express-static",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.12.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-23-express-static/public/github-octocat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-23-express-static/public/github-octocat.png
--------------------------------------------------------------------------------
/ex-23-express-static/public/hello.css:
--------------------------------------------------------------------------------
1 | .hello {
2 | color: red;
3 | }
4 |
--------------------------------------------------------------------------------
/ex-23-express-static/public/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Document
6 |
7 |
8 | Hello
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ex-23-express-static/public/hello.js:
--------------------------------------------------------------------------------
1 | console.log('hello')
2 |
--------------------------------------------------------------------------------
/ex-24-koa-static/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var serve = require('koa-static');
3 | var app = koa();
4 |
5 |
6 | app.use(serve('public'));
7 |
8 |
9 | app.listen(3000);
10 |
--------------------------------------------------------------------------------
/ex-24-koa-static/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-24-koa-static",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "koa": "^0.20.0",
14 | "koa-static": "^1.4.9"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-24-koa-static/public/github-octocat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-24-koa-static/public/github-octocat.png
--------------------------------------------------------------------------------
/ex-24-koa-static/public/hello.css:
--------------------------------------------------------------------------------
1 | .hello {
2 | color: red;
3 | }
4 |
--------------------------------------------------------------------------------
/ex-24-koa-static/public/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Document
6 |
7 |
8 | Hello
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ex-24-koa-static/public/hello.js:
--------------------------------------------------------------------------------
1 | console.log('hello')
2 |
--------------------------------------------------------------------------------
/ex-25-express-session/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var session = require('express-session');
3 | var app = express();
4 |
5 |
6 | app.use(session({
7 | secret: 'keyboard cat',
8 | resave: false,
9 | saveUninitialized: true
10 | }));
11 |
12 | app.get('/', function(req, res) {
13 | var sess = req.session;
14 | if (sess && sess.username) {
15 | res.send('Hello ' + sess.username);
16 | } else {
17 | res.send('Please login');
18 | }
19 | });
20 |
21 | app.get('/login', function(req, res) {
22 | req.session.username = req.query.username;
23 | res.redirect('/');
24 | });
25 |
26 | app.get('/logout', function(req, res) {
27 | req.session.destroy(function(err) {
28 | res.redirect('/');
29 | });
30 | });
31 |
32 | app.listen(3000);
33 |
--------------------------------------------------------------------------------
/ex-25-express-session/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-25-express-session",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.12.3",
14 | "express-session": "^1.11.1"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-26-koa-session/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var session = require('koa-session');
3 | var router = require('koa-router')();
4 | var app = koa();
5 |
6 |
7 | app.keys = [ 'some secret hurr' ];
8 | app.use(session(app));
9 |
10 | router.get('/', function *() {
11 | var sess = this.session;
12 | if (sess && sess.username) {
13 | this.body = 'Hello ' + sess.username;
14 | } else {
15 | this.body = 'Please login';
16 | }
17 | });
18 |
19 | router.get('/login', function *() {
20 | this.session.username = this.query.username;
21 | this.redirect('/');
22 | });
23 |
24 | router.get('/logout', function *() {
25 | this.session = null;
26 | this.redirect('/');
27 | });
28 |
29 | app.use(function *(next) {
30 | yield next;
31 | // Handle 404 upstream.
32 | var status = this.status || 404;
33 | if (status === 404) this.body = 'Page Not Found';
34 | });
35 |
36 | app.use(router.routes());
37 |
38 | app.listen(3000);
39 |
--------------------------------------------------------------------------------
/ex-26-koa-session/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-26-koa-session",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "koa": "^0.20.0",
14 | "koa-router": "^4.3.2",
15 | "koa-session": "^3.1.0"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ex-27-express-formidable/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var formidable = require('formidable');
3 | var app = express();
4 |
5 |
6 | app.post('/upload', function(req, res) {
7 | var form = new formidable.IncomingForm();
8 | form.uploadDir = 'upload';
9 | form.keepExtensions = true;
10 | form.parse(req, function(err, fields, files) {
11 | console.log(fields);
12 | console.log(files);
13 | res.json({fields: fields, files: files});
14 | });
15 | });
16 |
17 |
18 | app.use(function(req, res) {
19 | res.sendStatus(404);
20 | });
21 |
22 | app.listen(3000);
23 |
--------------------------------------------------------------------------------
/ex-27-express-formidable/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-27-express-formidable",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.12.3",
14 | "formidable": "^1.0.17"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-27-express-formidable/upload/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/ex-28-koa-formidable/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var Promise = require('bluebird');
3 | var formidable = require('formidable');
4 | var app = koa();
5 |
6 |
7 |
8 | app.use(function *() {
9 | var form = new formidable.IncomingForm();
10 | form.uploadDir = 'upload';
11 | form.keepExtensions = true;
12 | var parse = Promise.promisify(form.parse, form);
13 | var uploaded = yield parse(this.req);
14 | console.log(uploaded);
15 | this.body = uploaded;
16 | });
17 |
18 |
19 | app.listen(3000);
20 |
--------------------------------------------------------------------------------
/ex-28-koa-formidable/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-28-koa-formidable",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bluebird": "^2.9.25",
14 | "formidable": "^1.0.17",
15 | "koa": "^0.20.0"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ex-28-koa-formidable/upload/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/ex-29-express-multi-router/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var app = express();
3 |
4 | var accounts = express.Router();
5 | var apis = express.Router();
6 | var docs = express.Router();
7 |
8 | accounts.get('/', function(req, res) {
9 | res.send('Accounts');
10 | });
11 |
12 | apis.get('/', function(req, res) {
13 | res.send('Apis');
14 | });
15 |
16 | docs.get('/', function(req, res) {
17 | res.send('Docs');
18 | });
19 |
20 | app.use('/accounts', accounts);
21 | app.use('/apis', apis);
22 | app.use('/docs', docs);
23 |
24 | app.use(function(req, res) {
25 | res.sendStatus(404);
26 | });
27 |
28 | app.listen(3000);
29 |
--------------------------------------------------------------------------------
/ex-29-express-multi-router/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-29-express-multi-router",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.12.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-30-koa-multi-router/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var mount = require('koa-mount');
3 | var router = require('koa-router');
4 | var accounts = router();
5 | var apis = router();
6 | var docs = router();
7 | var app = koa();
8 |
9 |
10 | accounts.get('/', function *() {
11 | this.body = 'Accounts';
12 | });
13 |
14 | apis.get('/', function *() {
15 | this.body = 'Apis';
16 | });
17 |
18 | docs.get('/', function *() {
19 | this.body = 'Docs';
20 | });
21 |
22 | app.use(function *(next) {
23 | yield next;
24 | // Handle 404 upstream.
25 | var status = this.status || 404;
26 | if (status === 404) this.body = 'Page Not Found';
27 | });
28 |
29 | app.use(mount('/accounts', accounts.routes()))
30 | .use(mount('/apis', apis.routes()))
31 | .use(mount('/docs', docs.routes()));
32 |
33 |
34 | app.listen(3000);
35 |
--------------------------------------------------------------------------------
/ex-30-koa-multi-router/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-30-koa-multi-router",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "koa": "^0.20.0",
14 | "koa-mount": "^1.3.0",
15 | "koa-router": "^4.3.2"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ex-31-fs-read-koa-async-await/README.md:
--------------------------------------------------------------------------------
1 | es7 async functions are now supported when you enabled `app.experimental = true`.
2 |
3 | it uses `https://github.com/thenables/composition`. however, it was significantly slower and not production ready.
4 |
5 | See koa [#415](https://github.com/koajs/koa/issues/415), composition [#1](https://github.com/thenables/composition/issues/1)
6 |
--------------------------------------------------------------------------------
/ex-31-fs-read-koa-async-await/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var app = koa();
3 | var Promise = require('bluebird');
4 | var readFile = Promise.promisify(require('fs').readFile);
5 |
6 | app.experimental = true;
7 |
8 | // file is a Buffer
9 | app.use(async function() {
10 | var file = await readFile(__dirname + '/hello.txt');
11 | this.body = file.toString();
12 | });
13 |
14 | app.listen(3000);
15 |
--------------------------------------------------------------------------------
/ex-31-fs-read-koa-async-await/hello.txt:
--------------------------------------------------------------------------------
1 | Hello World!
2 |
--------------------------------------------------------------------------------
/ex-31-fs-read-koa-async-await/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-31-fs-read-koa-async-await",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators run.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "babel": "^5.2.6",
14 | "bluebird": "^2.9.25",
15 | "koa": "^0.20.0"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ex-31-fs-read-koa-async-await/run.js:
--------------------------------------------------------------------------------
1 | require('babel/register')({
2 | optional: ['asyncToGenerator']
3 | });
4 | require('./app');
5 |
--------------------------------------------------------------------------------
/ex-32-password/.gitignore:
--------------------------------------------------------------------------------
1 | password.json
2 |
--------------------------------------------------------------------------------
/ex-32-password/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var Promise = require('bluebird');
3 | var fs = Promise.promisifyAll(require('fs'));
4 |
5 | var app = express();
6 |
7 | var PASSWORD_FILE = './password.json';
8 |
9 | var exists = fs.existsSync(PASSWORD_FILE);
10 |
11 | if (!exists) {
12 | fs.writeFileSync(PASSWORD_FILE, '{}');
13 | }
14 |
15 |
16 | app.get('/signup', function(req, res) {
17 | var username = req.query.username;
18 | if (!username) {
19 | return res.send('need username');
20 | }
21 | var password = req.query.password;
22 | if (!password) {
23 | return res.send('need password');
24 | }
25 | fs.readFileAsync(PASSWORD_FILE)
26 | .then(function(buf) {
27 | return JSON.parse(buf.toString());
28 | })
29 | .then(function(list) {
30 | list[username] = password;
31 | return fs.writeFileAsync(PASSWORD_FILE, JSON.stringify(list));
32 | })
33 | .then(function() {
34 | res.send('success');
35 | });
36 | });
37 |
38 | app.get('/verify', function(req, res) {
39 | var username = req.query.username;
40 | if (!username) {
41 | return res.send('need username');
42 | }
43 | var password = req.query.password;
44 | if (!password) {
45 | return res.send('need password');
46 | }
47 | fs.readFileAsync(PASSWORD_FILE)
48 | .then(function(buf) {
49 | return JSON.parse(buf.toString());
50 | })
51 | .then(function(list) {
52 | if (password === list[username]) {
53 | res.send('match');
54 | } else {
55 | res.send('not match');
56 | }
57 | });
58 | });
59 |
60 |
61 | app.listen(3000);
62 |
63 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/ex-32-password/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-32-password",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bluebird": "^2.9.25",
14 | "express": "^4.12.3"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-33-password-bcrypt/.gitignore:
--------------------------------------------------------------------------------
1 | password.json
2 |
--------------------------------------------------------------------------------
/ex-33-password-bcrypt/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var Promise = require('bluebird');
3 | var fs = Promise.promisifyAll(require('fs'));
4 | var bcrypt = require('bcrypt');
5 | var hash = Promise.promisify(bcrypt.hash);
6 | var compare = Promise.promisify(bcrypt.compare);
7 |
8 | var app = express();
9 |
10 | var PASSWORD_FILE = './password.json';
11 |
12 | var exists = fs.existsSync(PASSWORD_FILE);
13 |
14 | if (!exists) {
15 | fs.writeFileSync(PASSWORD_FILE, '{}');
16 | }
17 |
18 |
19 | app.get('/signup', function(req, res) {
20 | var passwordList;
21 | var username = req.query.username;
22 | if (!username) {
23 | return res.send('need username');
24 | }
25 | var password = req.query.password;
26 | if (!password) {
27 | return res.send('need password');
28 | }
29 | fs.readFileAsync(PASSWORD_FILE)
30 | .then(function(buf) {
31 | return JSON.parse(buf.toString());
32 | })
33 | .then(function(list) {
34 | passwordList = list;
35 | return hash(password, 10);
36 | })
37 | .then(function(hashed) {
38 | passwordList[username] = hashed;
39 | return fs.writeFileAsync(PASSWORD_FILE, JSON.stringify(passwordList));
40 | })
41 | .then(function() {
42 | res.send('success');
43 | });
44 | });
45 |
46 | app.get('/verify', function(req, res) {
47 | var username = req.query.username;
48 | if (!username) {
49 | return res.send('need username');
50 | }
51 | var password = req.query.password;
52 | if (!password) {
53 | return res.send('need password');
54 | }
55 | fs.readFileAsync(PASSWORD_FILE)
56 | .then(function(buf) {
57 | return JSON.parse(buf.toString());
58 | })
59 | .then(function(list) {
60 | return compare(password, list[username] || '');
61 | })
62 | .then(function(match) {
63 | if (match) {
64 | res.send('match');
65 | } else {
66 | res.send('not match');
67 | }
68 | });
69 | });
70 |
71 |
72 | app.listen(3000);
73 |
74 |
75 |
76 |
77 |
--------------------------------------------------------------------------------
/ex-33-password-bcrypt/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-33-password-bcrypt",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bcrypt": "^0.8.2",
14 | "bluebird": "^2.9.25",
15 | "express": "^4.12.3"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ex-34-debug/README.md:
--------------------------------------------------------------------------------
1 | ### debug main
2 |
3 | `npm run debug-main` or `DEBUG=app:main node main.js`
4 |
5 | ### debug a
6 |
7 | `npm run debug-a` or `DEBUG=app:a node main.js`
8 |
9 | ### debug b
10 |
11 | `npm run debug-b` or `DEBUG=app:b node main.js`
12 |
13 | ### debug c
14 |
15 | `npm run debug-c` or `DEBUG=app:c node main.js`
16 |
17 | ### debug app
18 |
19 | `npm run debug-app` or `DEBUG=app:* node main.js`
20 |
21 | ### scripts
22 |
23 | ```json
24 | "scripts": {
25 | "start": "node main.js",
26 | "debug-main": "DEBUG=app:main node main.js",
27 | "debug-a": "DEBUG=app:a node main.js",
28 | "debug-b": "DEBUG=app:b node main.js",
29 | "debug-c": "DEBUG=app:c node main.js",
30 | "debug-app": "DEBUG=app:* node main.js",
31 | "test": "echo \"Error: no test specified\" && exit 1"
32 | },
33 | ```
34 |
--------------------------------------------------------------------------------
/ex-34-debug/a.js:
--------------------------------------------------------------------------------
1 | var debug = require('debug')('app:a');
2 |
3 | debug('this is a');
4 |
--------------------------------------------------------------------------------
/ex-34-debug/b.js:
--------------------------------------------------------------------------------
1 | var debug = require('debug')('app:b');
2 |
3 | debug('this is b');
4 |
--------------------------------------------------------------------------------
/ex-34-debug/c.js:
--------------------------------------------------------------------------------
1 | var debug = require('debug')('app:c');
2 |
3 | debug('this is c');
4 |
--------------------------------------------------------------------------------
/ex-34-debug/main.js:
--------------------------------------------------------------------------------
1 | var debug = require('debug')('app:main');
2 |
3 | require('./a');
4 | require('./b');
5 | require('./c');
6 |
7 | debug('this is main');
8 |
--------------------------------------------------------------------------------
/ex-34-debug/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-34-debug",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node main.js",
8 | "debug-main": "DEBUG=app:main node main.js",
9 | "debug-a": "DEBUG=app:a node main.js",
10 | "debug-b": "DEBUG=app:b node main.js",
11 | "debug-c": "DEBUG=app:c node main.js",
12 | "debug-app": "DEBUG=app:* node main.js",
13 | "test": "echo \"Error: no test specified\" && exit 1"
14 | },
15 | "author": "",
16 | "license": "ISC",
17 | "dependencies": {
18 | "debug": "^2.1.3"
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/ex-35-uuid-cuid-lodash.uniqueId/app.js:
--------------------------------------------------------------------------------
1 | var uuid = require('uuid');
2 | var cuid = require('cuid');
3 | var uniqueId = require('lodash').uniqueId;
4 |
5 | var PREFIX = 'prefix_';
6 |
7 | console.log('uuid: ', uuid.v4());
8 | console.log('cuid: ', cuid());
9 | console.log('lodash.uniqueId: ', uniqueId()); // unique in this process
10 | console.log('lodash.uniqueId with prefix: ', uniqueId(PREFIX));
11 |
--------------------------------------------------------------------------------
/ex-35-uuid-cuid-lodash.uniqueId/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-35-uuid-cuid-lodash.uniqueId",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "cuid": "^1.2.4",
14 | "lodash": "^3.8.0",
15 | "uuid": "^2.0.1"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ex-36-superagent-cheerio/app.js:
--------------------------------------------------------------------------------
1 | var request = require('superagent');
2 | var cheerio = require('cheerio');
3 |
4 | var URL = 'https://github.com/Chiara-yen/startLearningNodejs';
5 |
6 |
7 | request
8 | .get(URL)
9 | .query({ 'a': 1 }) // ?a=1, for demo
10 | .end(function(err, res) {
11 | var $;
12 | if (res.ok) {
13 | $ = cheerio.load(res.text);
14 | console.log($('.author a span').text() + '/' + $('.js-current-repository').text());
15 | } else {
16 | alert('Oh no! error ' + res.text);
17 | }
18 | });
19 |
--------------------------------------------------------------------------------
/ex-36-superagent-cheerio/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-36-superagent-cheerio",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "cheerio": "^0.19.0",
14 | "superagent": "^1.2.0"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-37-minimist/README.md:
--------------------------------------------------------------------------------
1 |
2 | ```
3 | node bin/program.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
4 | ```
5 |
6 | `-x 3 => x: 3`
7 |
8 | `-y 4 => y: 4`
9 |
10 | `-n5 => n: 5`
11 |
12 | `-abc => a: true, b: true, c: true`
13 |
14 | `--beep=boop => beep: 'boop'`
15 |
16 | `foo bar baz => _: [ 'foo', 'bar', 'baz' ]`
17 |
--------------------------------------------------------------------------------
/ex-37-minimist/bin/program.js:
--------------------------------------------------------------------------------
1 | var argv = require('minimist')(process.argv.slice(2));
2 | console.dir(argv);
3 |
--------------------------------------------------------------------------------
/ex-37-minimist/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-37-minimist",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "bin": {
7 | "ex-37-minimist": "program.js"
8 | },
9 | "scripts": {
10 | "example": "node bin/program.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz",
11 | "test": "echo \"Error: no test specified\" && exit 1"
12 | },
13 | "author": "",
14 | "license": "ISC",
15 | "dependencies": {
16 | "minimist": "^1.1.1"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ex-38-commander/README.md:
--------------------------------------------------------------------------------
1 |
2 | ### short cut
3 |
4 | ```
5 | npm run short-cut
6 | ```
7 |
8 | or
9 |
10 | ```
11 | node bin/program.js -p -P -b -c tim
12 | ```
13 |
14 | ```
15 | program.peppers => true
16 | program.pineapple => true
17 | program.bbqSauce => true
18 | program.cheese => 'tim'
19 | ```
20 |
21 | ### full option
22 |
23 | ```
24 | npm run full-option
25 | ```
26 |
27 | or
28 |
29 | ```
30 | node bin/program.js --peppers --pineapple --bbq-sauce --cheese tim
31 | ```
32 |
33 | ```
34 | program.peppers => true
35 | program.pineapple => true
36 | program.bbqSauce => true
37 | program.cheese => 'tim'
38 | ```
39 |
--------------------------------------------------------------------------------
/ex-38-commander/bin/program.js:
--------------------------------------------------------------------------------
1 | var program = require('commander');
2 |
3 | program
4 | .version('0.0.1')
5 | .option('-p, --peppers', 'Add peppers')
6 | .option('-P, --pineapple', 'Add pineapple')
7 | .option('-b, --bbq-sauce', 'Add bbq sauce')
8 | .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
9 | .parse(process.argv);
10 |
11 | if (program.peppers) console.log(' - peppers');
12 | if (program.pineapple) console.log(' - pineapple');
13 | if (program.bbqSauce) console.log(' - bbq');
14 | console.log(' - %s cheese', program.cheese);
15 |
--------------------------------------------------------------------------------
/ex-38-commander/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-38-commander",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "bin": {
7 | "ex-38-commander": "program.js"
8 | },
9 | "scripts": {
10 | "short-cut": "node bin/program.js -p -P -b -c tim",
11 | "full-option": "node bin/program.js --peppers --pineapple --bbq-sauce --cheese tim",
12 | "test": "echo \"Error: no test specified\" && exit 1"
13 | },
14 | "author": "",
15 | "license": "ISC",
16 | "dependencies": {
17 | "commander": "^2.8.1"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/ex-39-inquirer/bin/program.js:
--------------------------------------------------------------------------------
1 | var inquirer = require('inquirer');
2 |
3 | var times = 0;
4 |
5 | inquirer.prompt([
6 |
7 | // confirm
8 | {
9 | type: 'confirm',
10 | name: 'isTimHandsome',
11 | message: 'Is Tim handsome?',
12 | default: true
13 | },
14 |
15 | // list
16 | {
17 | type: 'list',
18 | name: 'who',
19 | message: 'What do you want to do?',
20 | choices: [
21 | 'Talk to Tim',
22 | 'Talk to Roth',
23 | new inquirer.Separator(),
24 | 'Talk to Randy',
25 | 'Talk to Chiara'
26 | ]
27 | },
28 |
29 | // input
30 | {
31 | type: 'input',
32 | name: 'first_name',
33 | message: 'What\'s your first name',
34 | default: function () { return 'Tim'; }
35 | },
36 | {
37 | type: 'input',
38 | name: 'last_name',
39 | message: 'What\'s your last name'
40 | },
41 | {
42 | type: 'input',
43 | name: 'phone',
44 | message: 'What\'s your phone number',
45 | validate: function( value ) {
46 | var pass = value.match(/^([01]{1})?[\-\.\s]?\(?(\d{3})\)?[\-\.\s]?(\d{3})[\-\.\s]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?){1}(?:\d+)?)?$/i);
47 | if (pass || times > 0) {
48 | return true;
49 | } else {
50 | times++;
51 | return 'Please enter a valid phone number';
52 | }
53 | }
54 | }
55 | ], function(answers) {
56 | console.log(JSON.stringify(answers, null, ' '));
57 | });
58 |
59 |
--------------------------------------------------------------------------------
/ex-39-inquirer/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-39-inquirer",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "bin": {
7 | "ex-39-inquirer": "program.js"
8 | },
9 | "scripts": {
10 | "start": "node bin/program.js",
11 | "test": "echo \"Error: no test specified\" && exit 1"
12 | },
13 | "author": "",
14 | "license": "ISC",
15 | "dependencies": {
16 | "inquirer": "^0.8.3"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ex-40-password-bcrypt-bson/.gitignore:
--------------------------------------------------------------------------------
1 | password.bson
2 |
--------------------------------------------------------------------------------
/ex-40-password-bcrypt-bson/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var Promise = require('bluebird');
3 | var fs = Promise.promisifyAll(require('fs'));
4 | var bcrypt = require('bcrypt');
5 | var hash = Promise.promisify(bcrypt.hash);
6 | var compare = Promise.promisify(bcrypt.compare);
7 | var bson = require('bson');
8 | var BSON = bson.BSONPure.BSON;
9 |
10 | var app = express();
11 |
12 | var PASSWORD_FILE = './password.bson';
13 |
14 | var exists = fs.existsSync(PASSWORD_FILE);
15 |
16 | if (!exists) {
17 | fs.writeFileSync(PASSWORD_FILE, BSON.serialize({}));
18 | }
19 |
20 |
21 | app.get('/signup', function(req, res) {
22 | var passwordList;
23 | var username = req.query.username;
24 | if (!username) {
25 | return res.send('need username');
26 | }
27 | var password = req.query.password;
28 | if (!password) {
29 | return res.send('need password');
30 | }
31 | fs.readFileAsync(PASSWORD_FILE)
32 | .then(function(buf) {
33 | return BSON.deserialize(buf);
34 | })
35 | .then(function(list) {
36 | passwordList = list;
37 | return hash(password, 10);
38 | })
39 | .then(function(hashed) {
40 | passwordList[username] = hashed;
41 | return fs.writeFileAsync(PASSWORD_FILE, BSON.serialize(passwordList));
42 | })
43 | .then(function() {
44 | res.send('success');
45 | });
46 | });
47 |
48 | app.get('/verify', function(req, res) {
49 | var username = req.query.username;
50 | if (!username) {
51 | return res.send('need username');
52 | }
53 | var password = req.query.password;
54 | if (!password) {
55 | return res.send('need password');
56 | }
57 | fs.readFileAsync(PASSWORD_FILE)
58 | .then(function(buf) {
59 | return BSON.deserialize(buf);
60 | })
61 | .then(function(list) {
62 | return compare(password, list[username] || '');
63 | })
64 | .then(function(match) {
65 | if (match) {
66 | res.send('match');
67 | } else {
68 | res.send('not match');
69 | }
70 | });
71 | });
72 |
73 |
74 | app.listen(3000);
75 |
76 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/ex-40-password-bcrypt-bson/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-40-password-bcrypt-bson",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bcrypt": "^0.8.2",
14 | "bluebird": "^2.9.25",
15 | "bson": "^0.3.1",
16 | "express": "^4.12.3"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ex-41-image-resize-gm/README.md:
--------------------------------------------------------------------------------
1 |
2 | First download and install [GraphicsMagick](http://www.graphicsmagick.org/)
3 |
4 | #### Assign width
5 |
6 | ```
7 | node bin/resize.js -w 2000 image/github-octocat.png
8 | ```
9 |
10 | or
11 |
12 | ```
13 | node bin/resize.js --width 2000 image/github-octocat.png
14 | ```
15 |
16 |
17 | #### Assign height
18 |
19 | ```
20 | node bin/resize.js -h 2000 image/github-octocat.png
21 | ```
22 |
23 | or
24 |
25 | ```
26 | node bin/resize.js --height 2000 image/github-octocat.png
27 | ```
28 |
29 |
--------------------------------------------------------------------------------
/ex-41-image-resize-gm/bin/resize.js:
--------------------------------------------------------------------------------
1 | var program = require('commander');
2 | var gm = require('gm');
3 |
4 | program
5 | .version('0.0.1')
6 | .option('-w, --width [value]', 'Add the specified width', '100')
7 | .option('-h, --height [value]', 'Add the specified height', '100')
8 | .parse(process.argv);
9 |
10 |
11 | var width = +program.width || +program.height || 100;
12 | var height = +program.height || +program.width || 100;
13 |
14 | console.log('width: ', width);
15 | console.log('height: ', height);
16 |
17 | var files = program.args;
18 | var file = files[0];
19 | var fileParts = file.split('/');
20 | var length = fileParts.length;
21 | var filename = fileParts[ length - 1 ];
22 |
23 | console.log('file: ', file);
24 | console.log('filename: ', filename);
25 |
26 | gm(file)
27 | .resize(width, height)
28 | .write('output/' + filename, function (err) {
29 | if (!err) console.log('done');
30 | });
31 |
--------------------------------------------------------------------------------
/ex-41-image-resize-gm/image/github-octocat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-41-image-resize-gm/image/github-octocat.png
--------------------------------------------------------------------------------
/ex-41-image-resize-gm/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/ex-41-image-resize-gm/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-41-image-resize-gm",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "bin": {
7 | "ex-41-image-resize-gm": "resize.js"
8 | },
9 | "scripts": {
10 | "test": "echo \"Error: no test specified\" && exit 1"
11 | },
12 | "author": "",
13 | "license": "ISC",
14 | "dependencies": {
15 | "commander": "^2.8.1",
16 | "gm": "^1.17.0"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ex-42-bluebird/all.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 |
3 | var p1 = generatePromise();
4 | var p2 = generatePromise();
5 | var p3 = generatePromise();
6 |
7 | Promise.all([ p1, p2, p3 ])
8 | .then(function(values) {
9 | console.log('values: ', values);
10 | }, function(err) {
11 | console.log('error: ', err);
12 | });
13 |
14 |
15 | function generatePromise() {
16 | return new Promise(function(resolve, reject) {
17 | setTimeout(function() {
18 | var val = Math.random();
19 | if (val > 0.2) {
20 | resolve('{"value": ' + val + '}');
21 | } else {
22 | reject(new Error('fail'));
23 | }
24 | }, 1000 * Math.random());
25 | });
26 | }
27 |
--------------------------------------------------------------------------------
/ex-42-bluebird/any.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 |
3 | var p1 = generatePromise();
4 | var p2 = generatePromise();
5 | var p3 = generatePromise();
6 |
7 | Promise.any([ p1, p2, p3 ])
8 | .then(function(val) {
9 | console.log('val: ', val);
10 | }, function(err) {
11 | console.log('error: ', err);
12 | });
13 |
14 |
15 | function generatePromise() {
16 | return new Promise(function(resolve, reject) {
17 | setTimeout(function() {
18 | var val = Math.random();
19 | if (val > 0.6) {
20 | resolve('{"value": ' + val + '}');
21 | } else {
22 | reject(new Error('fail'));
23 | }
24 | }, 1000 * Math.random());
25 | });
26 | }
27 |
28 |
--------------------------------------------------------------------------------
/ex-42-bluebird/cancel.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 |
3 | var p = new Promise(function(resolve, reject) {
4 | setTimeout(function() {
5 | var val = Math.random();
6 | if (val > 0.5) {
7 | resolve('{"value": ' + val + '}');
8 | } else {
9 | reject(new Error('fail'));
10 | }
11 | }, 5000);
12 | })
13 | .cancellable()
14 | .then(function(val) {
15 | console.log('object: ', JSON.parse(val));
16 | }, function(err) {
17 | console.log(err);
18 | });
19 |
20 | setTimeout(function() {
21 | p.cancel();
22 | }, 2500);
23 |
--------------------------------------------------------------------------------
/ex-42-bluebird/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-42-bluebird",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "all.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "bluebird": "^2.9.25"
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/ex-42-bluebird/promise.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 |
3 | var p = new Promise(function(resolve, reject) {
4 | setTimeout(function() {
5 | var val = Math.random();
6 | if (val > 0.5) {
7 | resolve('{"value": ' + val + '}');
8 | } else {
9 | reject(new Error('fail'));
10 | }
11 | }, 1000);
12 | })
13 | .then(function(val) {
14 | console.log('object: ', JSON.parse(val));
15 | }, function(err) {
16 | console.log(err);
17 | })
18 | .catch(SyntaxError, function(err) {
19 | console.log('SyntaxError catch', err);
20 | })
21 | .catch(function(err) {
22 | console.log('final catch', err);
23 | });
24 |
--------------------------------------------------------------------------------
/ex-42-bluebird/promisify.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 | var readFile = Promise.promisify(require('fs').readFile);
3 |
4 | readFile('promisify.js')
5 | .then(function(buf) {
6 | console.log(buf);
7 | });
8 |
--------------------------------------------------------------------------------
/ex-42-bluebird/some.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 |
3 | var Promise = require('bluebird');
4 |
5 | var p1 = generatePromise();
6 | var p2 = generatePromise();
7 | var p3 = generatePromise();
8 |
9 | Promise.some([ p1, p2, p3 ], 2)
10 | .then(function(val) {
11 | console.log('val: ', val);
12 | }, function(err) {
13 | console.log('error: ', err);
14 | });
15 |
16 |
17 | function generatePromise() {
18 | return new Promise(function(resolve, reject) {
19 | setTimeout(function() {
20 | var val = Math.random();
21 | if (val > 0.6) {
22 | resolve('{"value": ' + val + '}');
23 | } else {
24 | reject(new Error('fail'));
25 | }
26 | }, 1000 * Math.random());
27 | });
28 | }
29 |
30 |
--------------------------------------------------------------------------------
/ex-42-bluebird/spread.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 |
3 | var p1 = generatePromise();
4 | var p2 = generatePromise();
5 | var p3 = generatePromise();
6 |
7 | Promise.all([ p1, p2, p3 ])
8 | .spread(function(val1, val2, val3) {
9 | console.log('val1: ', val1);
10 | console.log('val2: ', val2);
11 | console.log('val3: ', val3);
12 | }, function(err) {
13 | console.log('error: ', err);
14 | });
15 |
16 |
17 | function generatePromise() {
18 | return new Promise(function(resolve, reject) {
19 | setTimeout(function() {
20 | var val = Math.random();
21 | if (val > 0.5) {
22 | resolve('{"value": ' + val + '}');
23 | } else {
24 | reject(new Error('fail'));
25 | }
26 | }, 1000 * Math.random());
27 | });
28 | }
29 |
--------------------------------------------------------------------------------
/ex-42-bluebird/timeout.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 |
3 | var p = new Promise(function(resolve, reject) {
4 | setTimeout(function() {
5 | var val = Math.random();
6 | if (val > 0.5) {
7 | resolve('{"value": ' + val + '}');
8 | } else {
9 | reject(new Error('fail'));
10 | }
11 | }, 5000);
12 | })
13 | .timeout(2500)
14 | .then(function(val) {
15 | console.log('object: ', JSON.parse(val));
16 | }, function(err) {
17 | console.log(err);
18 | });
19 |
20 |
--------------------------------------------------------------------------------
/ex-43-express-render-jade/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var path = require('path');
3 | var app = express();
4 |
5 | // view engine setup
6 | app.set('views', path.join(__dirname, 'views'));
7 | app.set('view engine', 'jade');
8 |
9 | app.get('/', function(req, res) {
10 | res.render('index', {
11 | title: req.query.title || 'Default Title',
12 | content: req.query.content || 'Default Content'
13 | });
14 | })
15 |
16 | app.listen(3000);
17 |
--------------------------------------------------------------------------------
/ex-43-express-render-jade/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-43-express-render-jade",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.12.3",
14 | "jade": "^1.9.2"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-43-express-render-jade/views/index.jade:
--------------------------------------------------------------------------------
1 | doctype html
2 | html
3 | head
4 | title= title
5 | body
6 | #app= content
7 |
--------------------------------------------------------------------------------
/ex-44-koa-render-jade/app.js:
--------------------------------------------------------------------------------
1 | var views = require('koa-views');
2 | var koa = require('koa');
3 | var app = koa();
4 |
5 | app.use(views('./views', { default: 'jade' }));
6 |
7 | app.use(function *() {
8 | yield this.render('index', {
9 | title: this.query.title || 'Default Title',
10 | content: this.query.content || 'Default Content'
11 | });
12 | });
13 |
14 | app.listen(3000);
15 |
--------------------------------------------------------------------------------
/ex-44-koa-render-jade/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-44-koa-render-jade",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "jade": "^1.9.2",
14 | "koa": "^0.20.0",
15 | "koa-views": "^3.0.0"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ex-44-koa-render-jade/views/index.jade:
--------------------------------------------------------------------------------
1 | doctype html
2 | html
3 | head
4 | title= title
5 | body
6 | #app= content
7 |
--------------------------------------------------------------------------------
/ex-45-csv/app.js:
--------------------------------------------------------------------------------
1 | var csv = require('csv');
2 | var Promise = require('bluebird');
3 | var generate = Promise.promisify(csv.generate);
4 | var parse = Promise.promisify(csv.parse);
5 | var stringify = Promise.promisify(csv.stringify);
6 |
7 |
8 | generate({ seed: 1, columns: 4, length: 5 })
9 | .then(function(data) {
10 | console.log('generate:\n', data);
11 | return parse(data);
12 | })
13 | .then(function(data) {
14 | console.log('parse:\n', data);
15 | return stringify(data);
16 | })
17 | .then(function(data) {
18 | console.log('stringify:\n', data);
19 | });
20 |
--------------------------------------------------------------------------------
/ex-45-csv/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-45-csv",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bluebird": "^2.9.25",
14 | "csv": "^0.4.2"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-46-markdown-marked/app.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var marked = require('marked');
3 |
4 | fs.readFile('../README.md', function(err, buf) {
5 | process.stdout.write(marked(buf.toString()));
6 | });
7 |
--------------------------------------------------------------------------------
/ex-46-markdown-marked/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-46-markdown-marked",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "marked": "^0.3.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-47-xml2js/app.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 | var parseString = Promise.promisify(require('xml2js').parseString);
3 | var readFile = Promise.promisify(require('fs').readFile);
4 |
5 | var FILE_PATH = './sample.xml';
6 |
7 | readFile(FILE_PATH)
8 | .then(function(buf) {
9 | var xml = buf.toString();
10 | return parseString(xml);
11 | })
12 | .then(function(result) {
13 | console.log(result);
14 | });
15 |
--------------------------------------------------------------------------------
/ex-47-xml2js/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-47-xml2js",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bluebird": "^2.9.25",
14 | "xml2js": "^0.4.8"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-47-xml2js/sample.xml:
--------------------------------------------------------------------------------
1 |
2 | Character data here!
3 |
4 |
5 |
6 |
7 |
8 | Line One
9 | Line Two
10 |
11 |
12 | -
13 | This Foo(1) is
14 | Foo(2)
15 | character
16 | Foo(3)
17 | data!
18 | Foo(4)
19 |
20 | - Qux.
21 | - Quux.
22 | Single
23 |
24 |
25 | - Baz.
26 | - Foo.Bar.
27 |
28 |
29 |
30 | something
31 | something else
32 | something third
33 |
34 |
35 | 1
36 | 2
37 | 3
38 | 4
39 | 5
40 | 6
41 |
42 |
43 |
44 |
45 | - Bar.
46 |
47 | 42
48 | 43
49 |
50 |
51 |
52 |
53 |
54 |
55 | some value
56 | this is text with markup in the middle
57 |
58 |
--------------------------------------------------------------------------------
/ex-48-glob/aaa.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-48-glob/aaa.js
--------------------------------------------------------------------------------
/ex-48-glob/app.js:
--------------------------------------------------------------------------------
1 | var glob = require('glob');
2 |
3 |
4 | glob('**/*.js', function(err, files) {
5 | console.log('**/*.js:\n', files);
6 |
7 | console.log('\n\n\n');
8 | });
9 |
10 | glob('**/tim.*', function(err, files) {
11 | console.log('**/tim.*:\n', files);
12 |
13 | console.log('\n\n\n');
14 | });
15 |
16 | glob('tim.*', function(err, files) {
17 | console.log('tim.*:\n', files);
18 |
19 | console.log('\n\n\n');
20 | });
21 |
--------------------------------------------------------------------------------
/ex-48-glob/bbb.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-48-glob/bbb.js
--------------------------------------------------------------------------------
/ex-48-glob/ccc.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-48-glob/ccc.js
--------------------------------------------------------------------------------
/ex-48-glob/examples/a.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-48-glob/examples/a.js
--------------------------------------------------------------------------------
/ex-48-glob/examples/b.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-48-glob/examples/b.js
--------------------------------------------------------------------------------
/ex-48-glob/examples/c.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-48-glob/examples/c.js
--------------------------------------------------------------------------------
/ex-48-glob/examples/tim.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-48-glob/examples/tim.css
--------------------------------------------------------------------------------
/ex-48-glob/examples/tim.html:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-48-glob/examples/tim.html
--------------------------------------------------------------------------------
/ex-48-glob/examples/tim.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-48-glob/examples/tim.js
--------------------------------------------------------------------------------
/ex-48-glob/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-48-glob",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "glob": "^5.0.5"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-48-glob/tim.min.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-48-glob/tim.min.js
--------------------------------------------------------------------------------
/ex-49-mkdirp-del-rimraf-touch/README.md:
--------------------------------------------------------------------------------
1 | #### Create tim.*
2 |
3 | ```bash
4 | node create.js
5 | ```
6 |
7 | #### Delete tim.*
8 |
9 | ```bash
10 | node delete.js
11 | ```
12 |
--------------------------------------------------------------------------------
/ex-49-mkdirp-del-rimraf-touch/create.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 | var touch = Promise.promisify(require('touch'));
3 |
4 | var EXAMPLE_DIR = 'example/';
5 |
6 | touch(EXAMPLE_DIR + 'tim.js')
7 | .then(function() {
8 | return touch(EXAMPLE_DIR + 'tim.php');
9 | })
10 | .then(function() {
11 | return touch(EXAMPLE_DIR + 'tim.css');
12 | })
13 | .then(function() {
14 | return touch(EXAMPLE_DIR + 'tim.java');
15 | })
16 | .then(function() {
17 | return touch(EXAMPLE_DIR + 'tim.min.css');
18 | })
19 | .then(function() {
20 | return touch(EXAMPLE_DIR + 'tim.min.js');
21 | })
22 | .then(function() {
23 | return touch(EXAMPLE_DIR + 'tim.rb');
24 | })
25 | .then(function() {
26 | return touch(EXAMPLE_DIR + 'tim.styl');
27 | })
28 | .then(function() {
29 | return touch(EXAMPLE_DIR + 'tim.py');
30 | })
31 | .then(function() {
32 | return touch(EXAMPLE_DIR + 'tim.go');
33 | })
34 | .then(function() {
35 | console.log('success');
36 | });
37 |
--------------------------------------------------------------------------------
/ex-49-mkdirp-del-rimraf-touch/delete.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 | var del = Promise.promisify(require('del'));
3 |
4 | var EXAMPLE_DIR = 'example/';
5 |
6 | del(EXAMPLE_DIR + 'tim.*')
7 | .then(function (paths) {
8 | console.log('Deleted files/folders:\n', paths.join('\n'));
9 | });
10 |
--------------------------------------------------------------------------------
/ex-49-mkdirp-del-rimraf-touch/example/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/ex-49-mkdirp-del-rimraf-touch/mkdir-p.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 | var mkdirp = Promise.promisify(require('mkdirp'));
3 |
4 | var EXAMPLE_DIR = 'example/';
5 |
6 | mkdirp(EXAMPLE_DIR + 'tmp/foo/bar/baz')
7 | .then(function () {
8 | console.log('success');
9 | });
10 |
--------------------------------------------------------------------------------
/ex-49-mkdirp-del-rimraf-touch/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-49-mkdirp-del-rimraf-touch",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "create.js",
6 | "scripts": {
7 | "create": "node create.js",
8 | "delete": "node delete.js",
9 | "mkdir-p": "node mkdir-p.js",
10 | "rm-rf": "node rm-rf.js",
11 | "test": "echo \"Error: no test specified\" && exit 1"
12 | },
13 | "author": "",
14 | "license": "ISC",
15 | "dependencies": {
16 | "bluebird": "^2.9.25",
17 | "del": "^1.1.1",
18 | "mkdirp": "^0.5.0",
19 | "rimraf": "^2.3.3",
20 | "touch": "0.0.3"
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/ex-49-mkdirp-del-rimraf-touch/rm-rf.js:
--------------------------------------------------------------------------------
1 | var Promise = require('bluebird');
2 | var rimraf = Promise.promisify(require('rimraf'));
3 |
4 | var EXAMPLE_DIR = 'example/';
5 |
6 | rimraf(EXAMPLE_DIR + 'tmp')
7 | .then(function () {
8 | console.log('success');
9 | });
10 |
--------------------------------------------------------------------------------
/ex-50-express-query-body-param/README.md:
--------------------------------------------------------------------------------
1 |
2 | `POST localhost:3000/users/100?user_id=200`
3 |
4 | body:
5 |
6 | `user_id=300`
7 |
8 | res json:
9 |
10 | ```json
11 | {
12 | "queryUserId": "200",
13 | "bodyUserId": "300",
14 | "paramUserId": "100"
15 | }
16 | ```
17 |
--------------------------------------------------------------------------------
/ex-50-express-query-body-param/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var bodyParser = require('body-parser');
3 | var app = express();
4 |
5 | app.use(bodyParser.urlencoded({ extended: false }));
6 | app.use(bodyParser.json());
7 |
8 | app.post('/users/:id', function(req, res) {
9 | var queryUserId = req.query.user_id;
10 | var bodyUserId = req.body.user_id;
11 | var paramUserId = req.params.id;
12 | res.json({
13 | queryUserId: queryUserId,
14 | bodyUserId: bodyUserId,
15 | paramUserId: paramUserId
16 | });
17 | });
18 |
19 | app.listen(3000);
20 |
--------------------------------------------------------------------------------
/ex-50-express-query-body-param/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-50-express-query-body-param",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "body-parser": "^1.12.3",
14 | "express": "^4.12.3"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-51-koa-query-body-param/README.md:
--------------------------------------------------------------------------------
1 |
2 | `POST localhost:3000/users/100?user_id=200`
3 |
4 | body:
5 |
6 | `user_id=300`
7 |
8 | res json:
9 |
10 | ```json
11 | {
12 | "queryUserId": "200",
13 | "bodyUserId": "300",
14 | "paramUserId": "100"
15 | }
16 | ```
17 |
--------------------------------------------------------------------------------
/ex-51-koa-query-body-param/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var router = require('koa-router')();
3 | var bodyParser = require('koa-bodyparser');
4 | var app = koa();
5 |
6 | app.use(bodyParser());
7 |
8 | router.post('/users/:id', function *() {
9 | var queryUserId = this.request.query.user_id;
10 | var bodyUserId = this.request.body.user_id;
11 | var paramUserId = this.params.id;
12 | this.body = {
13 | queryUserId: queryUserId,
14 | bodyUserId: bodyUserId,
15 | paramUserId: paramUserId
16 | };
17 | });
18 |
19 | app.use(router.routes());
20 |
21 |
22 | app.listen(3000);
23 |
--------------------------------------------------------------------------------
/ex-51-koa-query-body-param/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-51-koa-query-body-param",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "koa": "^0.20.0",
14 | "koa-bodyparser": "^1.6.0",
15 | "koa-router": "^4.3.2"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ex-52-node_env-nconf/app-nconf.js:
--------------------------------------------------------------------------------
1 | var nconf = require('nconf');
2 |
3 |
4 | nconf
5 | .argv()
6 | .env()
7 | .file({ file: 'config.json' });
8 |
9 | nconf.set('database:host', '127.0.0.1');
10 | nconf.set('database:port', 5984);
11 |
12 |
13 | console.log('key: ', nconf.get('key'));
14 | console.log('NODE_ENV: ', nconf.get('NODE_ENV'));
15 | console.log('database: ', nconf.get('database'));
16 | console.log('username: ', nconf.get('username'));
17 |
--------------------------------------------------------------------------------
/ex-52-node_env-nconf/app.js:
--------------------------------------------------------------------------------
1 | var ENV = process.env.NODE_ENV || 'development';
2 |
3 | console.log('Your environment is:\n');
4 |
5 | if (ENV === 'production') {
6 | console.log('production');
7 | } else if (ENV === 'development') {
8 | console.log('development');
9 | } else if (ENV === 'testing') {
10 | console.log('testing');
11 | } else {
12 | console.log('unrecognized');
13 | }
14 |
--------------------------------------------------------------------------------
/ex-52-node_env-nconf/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "database": {
3 | "name": "mysql"
4 | },
5 | "username": "tim"
6 | }
7 |
--------------------------------------------------------------------------------
/ex-52-node_env-nconf/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-52-node_env-nconf",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app-nconf.js",
6 | "scripts": {
7 | "production": "NODE_ENV=production node app.js",
8 | "development": "NODE_ENV=development node app.js",
9 | "testing": "NODE_ENV=testing node app.js",
10 | "unrecognized": "NODE_ENV=xxx node app.js",
11 | "nconf": "NODE_ENV=production node app-nconf.js --key 1234567890",
12 | "test": "echo \"Error: no test specified\" && exit 1"
13 | },
14 | "author": "",
15 | "license": "ISC",
16 | "dependencies": {
17 | "nconf": "^0.7.1"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/ex-53-validator/app.js:
--------------------------------------------------------------------------------
1 | var validator = require('validator');
2 |
3 | console.log('foo@bar.com\n', 'isEmail', validator.isEmail('foo@bar.com'));
4 | console.log('https://github.com/chriso/validator.js\n', 'isEmail', validator.isEmail('https://github.com/chriso/validator.js'));
5 |
6 |
7 | console.log('foo@bar.com\n', 'isURL', validator.isURL('foo@bar.com'));
8 | console.log('https://github.com/chriso/validator.js\n', 'isURL', validator.isURL('https://github.com/chriso/validator.js'));
9 |
10 |
11 | console.log('127.0.0.1\n', 'isIP', validator.isIP('127.0.0.1'));
12 | console.log('2001:DB8:2de:0:0:0:0:e13\n', 'isIP', validator.isIP('2001:DB8:2de:0:0:0:0:e13'));
13 | console.log('127001\n', 'isIP', validator.isIP('127001'));
14 |
15 |
16 | console.log('4716368472599727\n', 'isCreditCard', validator.isCreditCard('4716368472599727'));
17 | console.log('4321\n', 'isCreditCard', validator.isCreditCard('4321'));
18 |
19 |
20 | console.log('6b3a2b30-f2ee-11e4-b939-0800200c9a66\n', 'isUUID', validator.isUUID('6b3a2b30-f2ee-11e4-b939-0800200c9a66'));
21 | console.log('6b3a2b30-f2ee-11e4-b939\n', 'isUUID', validator.isUUID('6b3a2b30-f2ee-11e4-b939'));
22 |
23 |
24 | console.log('YXNkYXNkc2R2YWFzbG5rc2FkbnZsc2EnZHY=\n', 'isBase64', validator.isBase64('YXNkYXNkc2R2YWFzbG5rc2FkbnZsc2EnZHY='));
25 | console.log('asdasdsdvaaslnksadnvlsa"dv\n', 'isBase64', validator.isBase64('asdasdsdvaaslnksadnvlsa"dv'));
26 |
27 |
28 | console.log('ccc\n', 'isHexColor', validator.isHexColor('ccc'));
29 | console.log('ggg0000\n', 'isHexColor', validator.isHexColor('ggg0000'));
30 |
31 |
32 | console.log('ccc12312asdafas\n', 'isAlphanumeric', validator.isAlphanumeric('ccc12312asdafas'));
33 | console.log('ggg-0000\n', 'isAlphanumeric', validator.isAlphanumeric('ggg-0000'));
34 |
--------------------------------------------------------------------------------
/ex-53-validator/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-53-validator",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "validator": "^3.39.0"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-54-express-csrf/app.js:
--------------------------------------------------------------------------------
1 | var cookieParser = require('cookie-parser');
2 | var csrf = require('csurf');
3 | var bodyParser = require('body-parser');
4 | var express = require('express');
5 |
6 | // setup route middlewares
7 | var csrfProtection = csrf({ cookie: true });
8 |
9 | // create express app
10 | var app = express();
11 |
12 | // parse cookies
13 | // we need this because "cookie" is true in csrfProtection
14 | app.use(cookieParser());
15 | app.use(bodyParser.urlencoded({ extended: false }));
16 |
17 | app.use(csrfProtection);
18 |
19 | app.get('/form', function(req, res) {
20 | // pass the csrfToken to the view
21 | var html =
22 | '' +
23 | '' +
24 | '' +
25 | '' +
26 | 'Document' +
27 | '' +
28 | '' +
29 | '' +
34 | '' +
35 | '';
36 |
37 | res.send(html);
38 | });
39 |
40 | app.post('/process', function(req, res) {
41 | res.send('data is being processed');
42 | });
43 |
44 |
45 | app.listen(3000);
46 |
--------------------------------------------------------------------------------
/ex-54-express-csrf/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-54-express-csrf",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "body-parser": "^1.12.3",
14 | "cookie-parser": "^1.3.4",
15 | "csurf": "^1.8.1",
16 | "express": "^4.12.3"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ex-55-koa-csrf/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var csrf = require('koa-csrf');
3 | var session = require('koa-session');
4 | var bodyParser = require('koa-bodyparser');
5 | var router = require('koa-router')();
6 |
7 | var app = koa();
8 |
9 | app.use(bodyParser());
10 |
11 | app.keys = ['session secret'];
12 | app.use(session(app));
13 |
14 | csrf(app);
15 | app.use(csrf.middleware);
16 |
17 | router.get('/form', function *() {
18 | // pass the csrfToken to the view
19 | var html =
20 | '' +
21 | '' +
22 | '' +
23 | '' +
24 | 'Document' +
25 | '' +
26 | '' +
27 | '' +
32 | '' +
33 | '';
34 |
35 | this.body = html;
36 | });
37 |
38 | router.post('/process', function *() {
39 | this.body = 'data is being processed';
40 | });
41 |
42 | app.use(router.routes());
43 |
44 |
45 | app.listen(3000);
46 |
--------------------------------------------------------------------------------
/ex-55-koa-csrf/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-55-koa-csrf",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "koa": "^0.20.0",
14 | "koa-bodyparser": "^1.6.0",
15 | "koa-csrf": "^2.1.3",
16 | "koa-router": "^4.3.2",
17 | "koa-session": "^3.1.0"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/ex-56-express-gzip/app.js:
--------------------------------------------------------------------------------
1 | var compression = require('compression');
2 | var express = require('express');
3 | var app = express();
4 |
5 | // compress all requests
6 | app.use(compression());
7 |
8 | app.use(function(req, res) {
9 | var text = '';
10 | for (var i = 0; i < 10000; i++) {
11 | text += 'tim';
12 | }
13 | res.send(text);
14 | });
15 |
16 | app.listen(3000);
17 |
--------------------------------------------------------------------------------
/ex-56-express-gzip/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-56-express-gzip",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "compression": "^1.4.3",
14 | "express": "^4.12.3"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-57-koa-gzip/app.js:
--------------------------------------------------------------------------------
1 | var compress = require('koa-compress');
2 | var koa = require('koa');
3 | var app = koa();
4 |
5 |
6 | app.use(compress({
7 | filter: function (content_type) {
8 | return /text/i.test(content_type);
9 | },
10 | threshold: 2048,
11 | flush: require('zlib').Z_SYNC_FLUSH
12 | }));
13 |
14 |
15 | app.use(function *() {
16 | var text = '';
17 | for (var i = 0; i < 10000; i++) {
18 | text += 'tim';
19 | }
20 | this.body = text;
21 | });
22 |
23 | app.listen(3000);
24 |
--------------------------------------------------------------------------------
/ex-57-koa-gzip/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-57-koa-gzip",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "koa": "^0.20.0",
14 | "koa-compress": "^1.0.8"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-58-http-socket.io/app.js:
--------------------------------------------------------------------------------
1 | var server = require('http').createServer(handler);
2 | var io = require('socket.io')(server);
3 | var fs = require('fs');
4 |
5 | io.on('connection', function(socket) {
6 |
7 | socket.on('poke', function(data) {
8 | console.log('poke', data);
9 | });
10 |
11 | socket.on('disconnect', function() {
12 | console.log('disconnect');
13 | });
14 |
15 | boom();
16 |
17 | function boom() {
18 | var rand = Math.random();
19 | socket.emit('boom', rand);
20 |
21 | setTimeout(boom, rand * 5000);
22 | }
23 | });
24 |
25 | server.listen(3000);
26 |
27 |
28 | function handler(req, res) {
29 |
30 | if (req.url === '/index.js' & req.method === 'GET') {
31 | res.writeHead(200, { 'Content-Type': 'text/javascript;charset=utf-8' });
32 | fs.createReadStream('index.js').pipe(res);
33 | } else if (req.url === '/boom.jpg' & req.method === 'GET') {
34 | res.writeHead(200, { 'Content-Type': 'image/jpeg;' });
35 | fs.createReadStream('boom.jpg').pipe(res);
36 | } else {
37 | res.writeHead(200, { 'Content-Type': 'text/html' });
38 | fs.createReadStream('index.html').pipe(res);
39 | }
40 | }
41 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/ex-58-http-socket.io/boom.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-58-http-socket.io/boom.jpg
--------------------------------------------------------------------------------
/ex-58-http-socket.io/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Document
6 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/ex-58-http-socket.io/index.js:
--------------------------------------------------------------------------------
1 | var socket = io('http://localhost:3000');
2 |
3 | socket.on('boom', function (data) {
4 | console.log('boom', data);
5 | var boom = document.getElementById('boom');
6 | boom.style.opacity = data;
7 | setTimeout(function() {
8 | boom.style.opacity = 0;
9 | }, 1000);
10 | });
11 |
12 | poke();
13 |
14 | function poke() {
15 | var rand = Math.random();
16 | socket.emit('poke', rand);
17 |
18 | setTimeout(poke, rand * 5000);
19 | }
20 |
21 |
--------------------------------------------------------------------------------
/ex-58-http-socket.io/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-58-http-socket.io",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "socket.io": "^1.3.5"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-59-express-socket.io/app.js:
--------------------------------------------------------------------------------
1 | var app = require('express')();
2 | var server = require('http').Server(app);
3 | var io = require('socket.io')(server);
4 | var fs = require('fs');
5 |
6 | io.on('connection', function(socket) {
7 |
8 | socket.on('poke', function(data) {
9 | console.log('poke', data);
10 | });
11 |
12 | socket.on('disconnect', function() {
13 | console.log('disconnect');
14 | });
15 |
16 | boom();
17 |
18 | function boom() {
19 | var rand = Math.random();
20 | socket.emit('boom', rand);
21 |
22 | setTimeout(boom, rand * 5000);
23 | }
24 | });
25 |
26 | app.get('/index.js', function(req, res) {
27 | fs.createReadStream('index.js').pipe(res);
28 | });
29 |
30 | app.get('/boom.jpg', function(req, res) {
31 | fs.createReadStream('boom.jpg').pipe(res);
32 | });
33 |
34 | app.get('*', function(req, res) {
35 | fs.createReadStream('index.html').pipe(res);
36 | });
37 |
38 | server.listen(3000);
39 |
--------------------------------------------------------------------------------
/ex-59-express-socket.io/boom.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-59-express-socket.io/boom.jpg
--------------------------------------------------------------------------------
/ex-59-express-socket.io/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Document
6 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/ex-59-express-socket.io/index.js:
--------------------------------------------------------------------------------
1 | var socket = io('http://localhost:3000');
2 |
3 | socket.on('boom', function (data) {
4 | console.log('boom', data);
5 | var boom = document.getElementById('boom');
6 | boom.style.opacity = 1;
7 | setTimeout(function() {
8 | boom.style.opacity = 0;
9 | }, 1000);
10 | });
11 |
12 | poke();
13 |
14 | function poke() {
15 | var rand = Math.random();
16 | socket.emit('poke', rand);
17 |
18 | setTimeout(poke, rand * 5000);
19 | }
20 |
21 |
--------------------------------------------------------------------------------
/ex-59-express-socket.io/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-59-express-socket.io",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.12.3",
14 | "socket.io": "^1.3.5"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-60-koa-socket.io/app.js:
--------------------------------------------------------------------------------
1 | var app = require('koa')();
2 | var router = require('koa-router')();
3 | var fs = require('co-fs');
4 |
5 |
6 | router.get('/index.js', function *() {
7 | var buf = yield fs.readFile('index.js');
8 | this.type = 'text/javascript';
9 | this.body = buf.toString();
10 | });
11 |
12 | router.get('/boom.jpg', function *() {
13 | this.body = yield fs.readFile('boom.jpg');
14 | });
15 |
16 | router.get('/', function *() {
17 | var buf = yield fs.readFile('index.html');
18 | this.body = buf.toString();
19 | });
20 |
21 | app.use(router.routes());
22 |
23 | var server = require('http').Server(app.callback());
24 | var io = require('socket.io')(server);
25 |
26 | io.on('connection', function(socket) {
27 |
28 | socket.on('poke', function(data) {
29 | console.log('poke', data);
30 | });
31 |
32 | socket.on('disconnect', function() {
33 | console.log('disconnect');
34 | });
35 |
36 | boom();
37 |
38 | function boom() {
39 | var rand = Math.random();
40 | socket.emit('boom', rand);
41 |
42 | setTimeout(boom, rand * 5000);
43 | }
44 | });
45 |
46 | server.listen(3000);
47 |
--------------------------------------------------------------------------------
/ex-60-koa-socket.io/boom.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chiara-yen/startLearningNodejs/0c8910bfc0a12bcb0579f46f2c6d73a424db316f/ex-60-koa-socket.io/boom.jpg
--------------------------------------------------------------------------------
/ex-60-koa-socket.io/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Document
6 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/ex-60-koa-socket.io/index.js:
--------------------------------------------------------------------------------
1 | var socket = io('http://localhost:3000');
2 |
3 | socket.on('boom', function (data) {
4 | console.log('boom', data);
5 | var boom = document.getElementById('boom');
6 | boom.style.opacity = 1;
7 | setTimeout(function() {
8 | boom.style.opacity = 0;
9 | }, 1000);
10 | });
11 |
12 | poke();
13 |
14 | function poke() {
15 | var rand = Math.random();
16 | socket.emit('poke', rand);
17 |
18 | setTimeout(poke, rand * 5000);
19 | }
20 |
21 |
--------------------------------------------------------------------------------
/ex-60-koa-socket.io/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-60-koa-socket.io",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "co-fs": "^1.2.0",
14 | "koa": "^0.20.0",
15 | "koa-router": "^4.3.2",
16 | "socket.io": "^1.3.5"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ex-61-jsdom/app.js:
--------------------------------------------------------------------------------
1 | var jsdom = require('jsdom');
2 |
3 | var URL = 'https://github.com/Chiara-yen/startLearningNodejs';
4 |
5 | jsdom.env(
6 | URL,
7 | [ '//code.jquery.com/jquery.js' ],
8 | function (err, window) {
9 | console.log(window.$('.author a span').text() + '/' + window.$('.js-current-repository').text());
10 | }
11 | );
12 |
--------------------------------------------------------------------------------
/ex-61-jsdom/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-61-jsdom",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "jsdom": "^3.1.2"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-62-virtual-dom/app.js:
--------------------------------------------------------------------------------
1 | var jsdom = require('jsdom');
2 | var h = require('virtual-dom/h');
3 | var diff = require('virtual-dom/diff');
4 | var patch = require('virtual-dom/patch');
5 | var createElement = require('virtual-dom/create-element');
6 |
7 |
8 |
9 | jsdom.env(
10 | '',
11 | function (err, window) {
12 | // 1: Create a function that declares what the DOM should look like
13 | function render(count) {
14 | return h('div', {
15 | style: {
16 | textAlign: 'center',
17 | lineHeight: (100 + count) + 'px',
18 | border: '1px solid red',
19 | width: (100 + count) + 'px',
20 | height: (100 + count) + 'px'
21 | }
22 | }, [String(count)]);
23 | }
24 |
25 | // 2: Initialise the document
26 | var count = 0; // We need some app data. Here we just store a count.
27 |
28 | var tree = render(count); // We need an initial tree
29 | console.log('oldTree:\n', tree);
30 |
31 | var rootNode = createElement(tree); // Create an initial root DOM node ...
32 | window.document.body.appendChild(rootNode); // ... and it should be in the document
33 |
34 | // 3: Wire up the update logic
35 | count++;
36 |
37 | var newTree = render(count);
38 | console.log('newTree:\n', newTree);
39 |
40 | var patches = diff(tree, newTree);
41 | console.log('diff:\n', patches);
42 |
43 | rootNode = patch(rootNode, patches);
44 |
45 | tree = newTree;
46 |
47 |
48 | process.exit();
49 | }
50 |
51 |
52 | );
53 |
--------------------------------------------------------------------------------
/ex-62-virtual-dom/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-62-virtual-dom",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "jsdom": "^3.1.2",
14 | "virtual-dom": "^2.0.1"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-63-phantomjs/.gitignore:
--------------------------------------------------------------------------------
1 | github.png
2 |
--------------------------------------------------------------------------------
/ex-63-phantomjs/README.md:
--------------------------------------------------------------------------------
1 | #### Install
2 |
3 | ```bash
4 | npm i -g phantomjs
5 | ```
6 |
7 | or
8 |
9 | [Download](http://phantomjs.org/download.html) binary
10 |
--------------------------------------------------------------------------------
/ex-63-phantomjs/app.js:
--------------------------------------------------------------------------------
1 | var page = require('webpage').create();
2 | var system = require('system');
3 |
4 | var count = system.args[1] || 1;
5 |
6 | var URL = 'https://github.com/Chiara-yen/startLearningNodejs';
7 |
8 | page.onConsoleMessage = function(msg) {
9 | for (var i = 0; i < count; i++) {
10 | console.log(msg);
11 | }
12 | };
13 |
14 | page.open(URL, function(status) {
15 | if (status !== 'success') {
16 | return console.log('Unable to access network');
17 | }
18 |
19 | page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', function() {
20 |
21 | var OUTER_VARIABLE = {
22 | a: 1,
23 | b: 2,
24 | c: 3
25 | };
26 |
27 | page.evaluate(function(outer) {
28 | console.log('outer variable:');
29 | console.log(outer.a);
30 | console.log(outer.b);
31 | console.log(outer.c);
32 | console.log(window.$('.author a span').text() + '/' + window.$('.js-current-repository').text());
33 | }, OUTER_VARIABLE);
34 |
35 | page.render('github.png');
36 |
37 | phantom.exit();
38 |
39 | });
40 | });
41 |
--------------------------------------------------------------------------------
/ex-63-phantomjs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-63-phantomjs",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "phantomjs app.js 3",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC"
12 | }
13 |
--------------------------------------------------------------------------------
/ex-64-nightmare/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-64-nightmare",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "test.js",
6 | "scripts": {
7 | "test": "node test.js"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "nightmare": "^1.8.1"
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/ex-64-nightmare/test.js:
--------------------------------------------------------------------------------
1 | var Nightmare = require('nightmare');
2 |
3 | new Nightmare()
4 | .goto('https://github.com/Chiara-yen/startLearningNodejs')
5 | .type('.js-site-search-field', 'github nightmare')
6 | .click('.author a')
7 | .wait()
8 | .evaluate(function () {
9 | return document.querySelector('.vcard-username').innerText;
10 | }, function (name) {
11 | console.log('name:', name);
12 | })
13 | .run();
14 |
--------------------------------------------------------------------------------
/ex-65-proxyquire/a.js:
--------------------------------------------------------------------------------
1 | var b = require('./b');
2 |
3 | module.exports = function() {
4 | return b.showYourAnswer();
5 | };
6 |
--------------------------------------------------------------------------------
/ex-65-proxyquire/b.js:
--------------------------------------------------------------------------------
1 |
2 | // random answer
3 | module.exports = {
4 | showYourAnswer: function() {
5 | return Math.random();
6 | }
7 | };
8 |
--------------------------------------------------------------------------------
/ex-65-proxyquire/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-65-proxyquire",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "test.js",
6 | "scripts": {
7 | "test": "node test.js"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "proxyquire": "^1.4.0"
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/ex-65-proxyquire/test.js:
--------------------------------------------------------------------------------
1 | var proxyquire = require('proxyquire');
2 | var assert = require('assert');
3 | var stub = {};
4 |
5 | stub.showYourAnswer = function() { return 0.5; };
6 |
7 | var a = proxyquire('./a', { './b': stub });
8 |
9 |
10 | assert.equal(a(), 0.5);
11 | assert.equal(a(1), 0.5);
12 | assert.equal(a('try your best'), 0.5);
13 |
--------------------------------------------------------------------------------
/ex-66-istanbul/.gitignore:
--------------------------------------------------------------------------------
1 | # Code coverage
2 | coverage
3 |
--------------------------------------------------------------------------------
/ex-66-istanbul/math.js:
--------------------------------------------------------------------------------
1 | var math = module.exports = {};
2 |
3 | math.add = function(a, b) {
4 | throwWhenNotNumber(a);
5 | throwWhenNotNumber(b);
6 | return a + b;
7 | };
8 |
9 |
10 | math.subtract = function(a, b) {
11 | throwWhenNotNumber(a);
12 | throwWhenNotNumber(b);
13 | return a - b;
14 | };
15 |
16 |
17 | math.multiply = function(a, b) {
18 | throwWhenNotNumber(a);
19 | throwWhenNotNumber(b);
20 | return a * b;
21 | };
22 |
23 |
24 | math.divide = function(a, b) {
25 | throwWhenNotNumber(a);
26 | throwWhenNotNumber(b);
27 | throwWhenZero(b);
28 | return a / b;
29 | };
30 |
31 |
32 | function throwWhenNotNumber(num) {
33 | if (typeof num !== 'number') {
34 | throw new TypeError(num + ' is not a number');
35 | }
36 | }
37 |
38 | function throwWhenZero(num) {
39 | if (num === 0) {
40 | throw new Error('cant not be 0');
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/ex-66-istanbul/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-66-istanbul",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "test": "node node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha --report lcovonly -- --reporter dot"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "chai": "^2.3.0",
13 | "istanbul": "^0.3.13",
14 | "mocha": "^2.2.4"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-66-istanbul/test/test.js:
--------------------------------------------------------------------------------
1 | var expect = require('chai').expect;
2 | var math = require('../math');
3 |
4 | describe('add', function () {
5 | it('should throw when first argument not number', function() {
6 | try {
7 | math.add('a', 1);
8 | } catch (e) {
9 | expect(e.message).is.equal('a is not a number');
10 | }
11 | });
12 |
13 | it('should throw when second argument not number', function() {
14 | try {
15 | math.add(1, 'b');
16 | } catch (e) {
17 | expect(e.message).is.equal('b is not a number');
18 | }
19 | });
20 |
21 | it('should work with positive', function() {
22 | var result = math.add(1, 2);
23 | expect(result).is.equal(3);
24 | });
25 |
26 | it('should work with 0', function() {
27 | var result = math.add(0, 0);
28 | expect(result).is.equal(0);
29 | });
30 |
31 | it('should work with negative', function() {
32 | var result = math.add(-1, -2);
33 | expect(result).is.equal(-3);
34 | });
35 | });
36 |
37 |
38 | describe('subtract', function () {
39 | it('should throw when first argument not number', function() {
40 | try {
41 | math.subtract('a', 1);
42 | } catch (e) {
43 | expect(e.message).is.equal('a is not a number');
44 | }
45 | });
46 |
47 | it('should throw when second argument not number', function() {
48 | try {
49 | math.subtract(1, 'b');
50 | } catch (e) {
51 | expect(e.message).is.equal('b is not a number');
52 | }
53 | });
54 |
55 | it('should work with positive', function() {
56 | var result = math.subtract(5, 2);
57 | expect(result).is.equal(3);
58 | });
59 |
60 | it('should work with 0', function() {
61 | var result = math.subtract(0, 0);
62 | expect(result).is.equal(0);
63 | });
64 |
65 | it('should work with negative', function() {
66 | var result = math.subtract(-1, -2);
67 | expect(result).is.equal(1);
68 | });
69 | });
70 |
71 | describe('multiply', function () {
72 | it('should throw when first argument not number', function() {
73 | try {
74 | math.multiply('a', 1);
75 | } catch (e) {
76 | expect(e.message).is.equal('a is not a number');
77 | }
78 | });
79 |
80 | it('should throw when second argument not number', function() {
81 | try {
82 | math.multiply(1, 'b');
83 | } catch (e) {
84 | expect(e.message).is.equal('b is not a number');
85 | }
86 | });
87 |
88 | it('should work with positive', function() {
89 | var result = math.multiply(5, 2);
90 | expect(result).is.equal(10);
91 | });
92 |
93 | it('should work with 0', function() {
94 | var result = math.multiply(5, 0);
95 | expect(result).is.equal(0);
96 | });
97 |
98 | it('should work with negative', function() {
99 | var result = math.multiply(-1, -2);
100 | expect(result).is.equal(2);
101 | });
102 | });
103 |
104 | describe('divide', function () {
105 | it('should throw when first argument not number', function() {
106 | try {
107 | math.divide('a', 1);
108 | } catch (e) {
109 | expect(e.message).is.equal('a is not a number');
110 | }
111 | });
112 |
113 | it('should throw when second argument not number', function() {
114 | try {
115 | math.divide(1, 'b');
116 | } catch (e) {
117 | expect(e.message).is.equal('b is not a number');
118 | }
119 | });
120 |
121 | it('should throw when divide by 0', function() {
122 | try {
123 | math.divide(5, 0);
124 | } catch (e) {
125 | expect(e.message).is.equal('cant not be 0');
126 | }
127 | });
128 |
129 | it('should work with positive', function() {
130 | var result = math.divide(5, 2);
131 | expect(result).is.equal(5/2);
132 | });
133 |
134 | it('should work with negative', function() {
135 | var result = math.divide(-1, -2);
136 | expect(result).is.equal(1/2);
137 | });
138 | });
139 |
--------------------------------------------------------------------------------
/ex-67-travis-ci/README.md:
--------------------------------------------------------------------------------
1 | see `.travis.yml`
2 |
3 | ```yml
4 | script: "npm run test-travis"
5 | ```
6 |
--------------------------------------------------------------------------------
/ex-67-travis-ci/math.js:
--------------------------------------------------------------------------------
1 | var math = module.exports = {};
2 |
3 | math.add = function(a, b) {
4 | throwWhenNotNumber(a);
5 | throwWhenNotNumber(b);
6 | return a + b;
7 | };
8 |
9 |
10 | math.subtract = function(a, b) {
11 | throwWhenNotNumber(a);
12 | throwWhenNotNumber(b);
13 | return a - b;
14 | };
15 |
16 |
17 | math.multiply = function(a, b) {
18 | throwWhenNotNumber(a);
19 | throwWhenNotNumber(b);
20 | return a * b;
21 | };
22 |
23 |
24 | math.divide = function(a, b) {
25 | throwWhenNotNumber(a);
26 | throwWhenNotNumber(b);
27 | throwWhenZero(b);
28 | return a / b;
29 | };
30 |
31 |
32 | function throwWhenNotNumber(num) {
33 | if (typeof num !== 'number') {
34 | throw new TypeError(num + ' is not a number');
35 | }
36 | }
37 |
38 | function throwWhenZero(num) {
39 | if (num === 0) {
40 | throw new Error('cant not be 0');
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/ex-67-travis-ci/test/test.js:
--------------------------------------------------------------------------------
1 | var expect = require('chai').expect;
2 | var math = require('../math');
3 |
4 | describe('add', function () {
5 | it('should throw when first argument not number', function() {
6 | try {
7 | math.add('a', 1);
8 | } catch (e) {
9 | expect(e.message).is.equal('a is not a number');
10 | }
11 | });
12 |
13 | it('should throw when second argument not number', function() {
14 | try {
15 | math.add(1, 'b');
16 | } catch (e) {
17 | expect(e.message).is.equal('b is not a number');
18 | }
19 | });
20 |
21 | it('should work with positive', function() {
22 | var result = math.add(1, 2);
23 | expect(result).is.equal(3);
24 | });
25 |
26 | it('should work with 0', function() {
27 | var result = math.add(0, 0);
28 | expect(result).is.equal(0);
29 | });
30 |
31 | it('should work with negative', function() {
32 | var result = math.add(-1, -2);
33 | expect(result).is.equal(-3);
34 | });
35 | });
36 |
37 |
38 | describe('subtract', function () {
39 | it('should throw when first argument not number', function() {
40 | try {
41 | math.subtract('a', 1);
42 | } catch (e) {
43 | expect(e.message).is.equal('a is not a number');
44 | }
45 | });
46 |
47 | it('should throw when second argument not number', function() {
48 | try {
49 | math.subtract(1, 'b');
50 | } catch (e) {
51 | expect(e.message).is.equal('b is not a number');
52 | }
53 | });
54 |
55 | it('should work with positive', function() {
56 | var result = math.subtract(5, 2);
57 | expect(result).is.equal(3);
58 | });
59 |
60 | it('should work with 0', function() {
61 | var result = math.subtract(0, 0);
62 | expect(result).is.equal(0);
63 | });
64 |
65 | it('should work with negative', function() {
66 | var result = math.subtract(-1, -2);
67 | expect(result).is.equal(1);
68 | });
69 | });
70 |
71 | describe('multiply', function () {
72 | it('should throw when first argument not number', function() {
73 | try {
74 | math.multiply('a', 1);
75 | } catch (e) {
76 | expect(e.message).is.equal('a is not a number');
77 | }
78 | });
79 |
80 | it('should throw when second argument not number', function() {
81 | try {
82 | math.multiply(1, 'b');
83 | } catch (e) {
84 | expect(e.message).is.equal('b is not a number');
85 | }
86 | });
87 |
88 | it('should work with positive', function() {
89 | var result = math.multiply(5, 2);
90 | expect(result).is.equal(10);
91 | });
92 |
93 | it('should work with 0', function() {
94 | var result = math.multiply(5, 0);
95 | expect(result).is.equal(0);
96 | });
97 |
98 | it('should work with negative', function() {
99 | var result = math.multiply(-1, -2);
100 | expect(result).is.equal(2);
101 | });
102 | });
103 |
104 | describe('divide', function () {
105 | it('should throw when first argument not number', function() {
106 | try {
107 | math.divide('a', 1);
108 | } catch (e) {
109 | expect(e.message).is.equal('a is not a number');
110 | }
111 | });
112 |
113 | it('should throw when second argument not number', function() {
114 | try {
115 | math.divide(1, 'b');
116 | } catch (e) {
117 | expect(e.message).is.equal('b is not a number');
118 | }
119 | });
120 |
121 | it('should throw when divide by 0', function() {
122 | try {
123 | math.divide(5, 0);
124 | } catch (e) {
125 | expect(e.message).is.equal('cant not be 0');
126 | }
127 | });
128 |
129 | it('should work with positive', function() {
130 | var result = math.divide(5, 2);
131 | expect(result).is.equal(5/2);
132 | });
133 |
134 | it('should work with negative', function() {
135 | var result = math.divide(-1, -2);
136 | expect(result).is.equal(1/2);
137 | });
138 | });
139 |
--------------------------------------------------------------------------------
/ex-68-sinon/a.txt:
--------------------------------------------------------------------------------
1 | ya!
--------------------------------------------------------------------------------
/ex-68-sinon/fake-timer.js:
--------------------------------------------------------------------------------
1 | var sinon = require('sinon');
2 |
3 | var clock = sinon.useFakeTimers();
4 |
5 | console.log('start.');
6 |
7 | setTimeout(function() {
8 | console.log('1000ms done.');
9 | }, 1000)
10 |
11 | clock.tick(1000);
12 |
13 | clock.restore();
14 |
--------------------------------------------------------------------------------
/ex-68-sinon/fs-proxy.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 |
3 | exports = module.exports = {};
4 |
5 | exports.writeFile = function() {
6 | fs.writeFile.apply(fs, [].slice.apply(arguments));
7 | };
8 |
--------------------------------------------------------------------------------
/ex-68-sinon/once.js:
--------------------------------------------------------------------------------
1 | module.exports = function once(fn) {
2 | var returnValue, called = false;
3 | return function () {
4 | if (!called) {
5 | called = true;
6 | returnValue = fn.apply(this, arguments);
7 | }
8 | return returnValue;
9 | };
10 | };
11 |
--------------------------------------------------------------------------------
/ex-68-sinon/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-68-sinon",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "ajax.js",
6 | "scripts": {
7 | "timer": "node fake-timer.js",
8 | "test": "mocha"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "devDependencies": {
13 | "chai": "^2.3.0",
14 | "mocha": "^2.2.4",
15 | "sinon": "^1.14.1"
16 | },
17 | "dependencies": {
18 | "jquery": "^2.1.4",
19 | "jsdom": "^3.1.2"
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/ex-68-sinon/random-throw.js:
--------------------------------------------------------------------------------
1 | exports = module.exports = {};
2 |
3 | exports.run = function() {
4 | var rand = Math.random();
5 | if (rand > 0.5) {
6 | throw new Error('ERROR!!!');
7 | } else {
8 | return rand;
9 | }
10 | };
11 |
--------------------------------------------------------------------------------
/ex-68-sinon/random.js:
--------------------------------------------------------------------------------
1 | exports = module.exports = {};
2 |
3 | exports.times = function(times) {
4 | return Math.random() * times;
5 | };
6 |
--------------------------------------------------------------------------------
/ex-68-sinon/test/spy.js:
--------------------------------------------------------------------------------
1 | var expect = require('chai').expect;
2 | var sinon = require('sinon');
3 | var once = require('../once');
4 | var fsProxy = require('../fs-proxy');
5 | var fs = require('fs');
6 |
7 |
8 | describe('once', function() {
9 |
10 | it('calls the original function', function() {
11 | var callback = sinon.spy();
12 | var proxy = once(callback);
13 |
14 | proxy();
15 |
16 | expect(callback.called).to.be.true;
17 | });
18 |
19 | it('calls the original function only once', function () {
20 | var callback = sinon.spy();
21 | var proxy = once(callback);
22 |
23 | proxy();
24 | proxy();
25 |
26 | expect(callback.calledOnce).to.be.true;
27 | // ...or:
28 | // assert.equals(callback.callCount, 1);
29 | });
30 |
31 | it('calls original function with right this and args', function () {
32 | var callback = sinon.spy();
33 | var proxy = once(callback);
34 | var obj = {};
35 |
36 | proxy.call(obj, 1, 2, 3);
37 |
38 | expect(callback.calledOn(obj)).to.be.true;
39 | expect(callback.calledWith(1, 2, 3)).to.be.true;
40 | });
41 | });
42 |
43 |
44 | describe('fsProxy', function() {
45 |
46 | before(function() {
47 | sinon.spy(fs, 'writeFile');
48 | });
49 |
50 | after(function() {
51 | fs.writeFile.restore();
52 | });
53 |
54 | it('calls the fs write', function () {
55 | fsProxy.writeFile('./a.txt', 'ya!');
56 | expect(fs.writeFile.calledOnce).to.be.true;
57 | expect(fs.writeFile.getCall(0).args[0]).to.be.equal('./a.txt');
58 | expect(fs.writeFile.getCall(0).args[1]).to.be.equal('ya!');
59 | });
60 | });
61 |
--------------------------------------------------------------------------------
/ex-68-sinon/test/stub.js:
--------------------------------------------------------------------------------
1 | var expect = require('chai').expect;
2 | var sinon = require('sinon');
3 | var randomThrow = require('../random-throw');
4 | var aTry = require('../try');
5 | var random = require('../random');
6 |
7 |
8 | describe('try', function() {
9 | afterEach(function() {
10 | randomThrow.run.restore();
11 | });
12 |
13 | it('throw error', function() {
14 | var stub = sinon.stub(randomThrow, 'run').throws();
15 | try {
16 | aTry();
17 | } catch (e) {
18 | expect(e.constructor.name).to.be.equal('Error');
19 | }
20 | });
21 |
22 | it('not throws error', function() {
23 | var stub = sinon.stub(randomThrow, 'run').returns(0.3);
24 | var pass, result;
25 | try {
26 | result = aTry();
27 | pass = true;
28 | } catch (e) {
29 |
30 | }
31 | expect(pass).to.be.true;
32 | expect(result).to.be.equal(0.3);
33 | });
34 |
35 | });
36 |
37 | describe('random', function() {
38 | afterEach(function() {
39 | Math.random.restore();
40 | });
41 |
42 | it('call multi-time', function() {
43 | var stub = sinon.stub(Math, 'random');
44 | stub.onCall(0).returns(0.35);
45 | stub.onCall(1).returns(0.56);
46 | stub.onCall(2).returns(0.91);
47 |
48 | expect(random.times(2)).to.be.equal(0.35 * 2);
49 | expect(random.times(3)).to.be.equal(0.56 * 3);
50 | expect(random.times(1)).to.be.equal(0.91);
51 | });
52 |
53 | });
54 |
--------------------------------------------------------------------------------
/ex-68-sinon/try.js:
--------------------------------------------------------------------------------
1 | var randomThrow = require('./random-throw');
2 |
3 | module.exports = function() {
4 | return randomThrow.run();
5 | };
6 |
--------------------------------------------------------------------------------
/ex-69-coveralls/README.md:
--------------------------------------------------------------------------------
1 | see `.travis.yml`
2 |
3 | ```yml
4 | after_script: "npm install coveralls@2 && cat ./coverage/lcov.info | coveralls"
5 | ```
6 |
--------------------------------------------------------------------------------
/ex-70-mocha-nightmare/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-70-mocha-nightmare",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "test.js",
6 | "scripts": {
7 | "test": "mocha test.js"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "chai": "^2.3.0",
13 | "mocha": "^2.2.4",
14 | "nightmare": "^1.8.1"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-70-mocha-nightmare/test.js:
--------------------------------------------------------------------------------
1 | var Nightmare = require('nightmare');
2 | var expect = require('chai').expect;
3 |
4 | describe('test github webpage', function() {
5 | this.timeout(30000);
6 |
7 | it('link page should display author', function(done) {
8 | new Nightmare()
9 | .goto('https://github.com/Chiara-yen/startLearningNodejs')
10 | .click('.author a')
11 | .wait()
12 | .evaluate(function () {
13 | return document.querySelector('.vcard-username').innerText;
14 | }, function (name) {
15 | expect(name).to.equal('Chiara-yen');
16 | })
17 | .run(done);
18 | });
19 | });
20 |
--------------------------------------------------------------------------------
/ex-71-node-blocked/app.js:
--------------------------------------------------------------------------------
1 | var blocked = require('blocked');
2 |
3 | setInterval(function() {
4 | Array(10000000).join('a');
5 | }, 500);
6 |
7 | setInterval(function() {
8 | Array(100000000).join('a');
9 | }, 3000);
10 |
11 | blocked(function(ms) {
12 | console.log('BLOCKED FOR %sms', ms | 0);
13 | });
14 |
--------------------------------------------------------------------------------
/ex-71-node-blocked/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-71-node-blocked",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "blocked": "^1.1.0"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-72-esprima/app.js:
--------------------------------------------------------------------------------
1 | var esprima = require('esprima');
2 |
3 |
4 | var CODE = 'var answer = 42';
5 |
6 |
7 |
8 | var syntax = esprima.parse(CODE);
9 |
10 | console.log('syntax:\n', syntax);
11 |
12 | // {
13 | // type: 'Program',
14 | // body: [
15 | // {
16 | // type: 'VariableDeclaration',
17 | // declarations: [
18 | // {
19 | // type: 'AssignmentExpression',
20 | // operator: =,
21 | // left: {
22 | // type: 'Identifier',
23 | // name: 'answer'
24 | // },
25 | // right: {
26 | // type: 'Literal',
27 | // value: 42
28 | // }
29 | // }
30 | // ]
31 | // }
32 | // ]
33 | // }
34 |
35 |
36 | var token = esprima.tokenize(CODE);
37 |
38 | console.log('token:\n', token);
39 |
40 | // [
41 | // { type: 'Keyword', value: 'var' },
42 | // { type: 'Identifier', value: 'answer' },
43 | // { type: 'Punctuator', value: '=' },
44 | // { type: 'Numeric', value: '42' }
45 | // ]
46 |
--------------------------------------------------------------------------------
/ex-72-esprima/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-72-esprima",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "basic.js",
6 | "scripts": {
7 | "app": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "esprima": "^2.2.0"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-73-simple-peer/app.js:
--------------------------------------------------------------------------------
1 | var SimplePeer = require('simple-peer');
2 | var wrtc = require('wrtc');
3 |
4 | var peer1 = new SimplePeer({ initiator: true, wrtc: wrtc });
5 | var peer2 = new SimplePeer({ wrtc: wrtc });
6 |
7 | peer1.on('signal', function (data) {
8 | // when peer1 has signaling data, give it to peer2
9 | console.log('peer1 on signal', data);
10 | peer2.signal(data);
11 | });
12 |
13 | peer2.on('signal', function (data) {
14 | // same as above, but in reverse
15 | console.log('peer2 on signal', data);
16 | peer1.signal(data);
17 | });
18 |
19 | peer1.on('connect', function () {
20 | // wait for 'connect' event before using the data channel
21 | console.log('peer1 on connect');
22 | peer1.send('hey peer2, how is it going?');
23 | });
24 |
25 | peer2.on('data', function (data) {
26 | // got a data channel message
27 | console.log('peer2 on data', data);
28 | console.log('got a message from peer1: ' + data);
29 | });
30 |
--------------------------------------------------------------------------------
/ex-73-simple-peer/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-73-simple-peer",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "app": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "simple-peer": "^5.4.3",
14 | "wrtc": "0.0.55"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-74-consolidate/ejs.js:
--------------------------------------------------------------------------------
1 | var cons = require('consolidate');
2 |
3 | cons.ejs('views/index.ejs', { title: 'Tim', text: 'My App' }, function(err, html) {
4 | if (err) throw err;
5 | console.log(html);
6 | });
7 |
--------------------------------------------------------------------------------
/ex-74-consolidate/haml.js:
--------------------------------------------------------------------------------
1 | var cons = require('consolidate');
2 |
3 | cons.haml('views/index.haml', { title: 'Tim', text: 'My App' }, function(err, html) {
4 | if (err) throw err;
5 | console.log(html);
6 | });
7 |
--------------------------------------------------------------------------------
/ex-74-consolidate/handlebars.js:
--------------------------------------------------------------------------------
1 | var cons = require('consolidate');
2 |
3 | cons.handlebars('views/index.hbs', { title: 'Tim', text: 'My App' }, function(err, html) {
4 | if (err) throw err;
5 | console.log(html);
6 | });
7 |
--------------------------------------------------------------------------------
/ex-74-consolidate/jade.js:
--------------------------------------------------------------------------------
1 | var cons = require('consolidate');
2 |
3 | cons.jade('views/index.jade', { title: 'Tim', text: 'My App' }, function(err, html) {
4 | if (err) throw err;
5 | console.log(html);
6 | });
7 |
--------------------------------------------------------------------------------
/ex-74-consolidate/lodash.js:
--------------------------------------------------------------------------------
1 | var cons = require('consolidate');
2 |
3 | cons.lodash('views/index.lodash', { title: 'Tim', text: 'My App' }, function(err, html) {
4 | if (err) throw err;
5 | console.log(html);
6 | });
7 |
--------------------------------------------------------------------------------
/ex-74-consolidate/mustache.js:
--------------------------------------------------------------------------------
1 | var cons = require('consolidate');
2 |
3 | cons.mustache('views/index.mustache', { title: 'Tim', text: 'My App' }, function(err, html) {
4 | if (err) throw err;
5 | console.log(html);
6 | });
7 |
--------------------------------------------------------------------------------
/ex-74-consolidate/nunjucks.js:
--------------------------------------------------------------------------------
1 | var cons = require('consolidate');
2 |
3 | cons.nunjucks('views/index.html', { title: 'Tim', text: 'My App' }, function(err, html) {
4 | if (err) throw err;
5 | console.log(html);
6 | });
7 |
--------------------------------------------------------------------------------
/ex-74-consolidate/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-74-consolidate",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "ejs.js",
6 | "scripts": {
7 | "ejs": "node ejs.js",
8 | "haml": "node haml.js",
9 | "handlebars": "node handlebars.js",
10 | "jade": "node jade.js",
11 | "lodash": "node lodash.js",
12 | "mustache": "node mustache.js",
13 | "nunjucks": "node nunjucks.js",
14 | "react": "node react.js",
15 | "swig": "node swig.js",
16 | "test": "echo \"Error: no test specified\" && exit 1"
17 | },
18 | "author": "",
19 | "license": "ISC",
20 | "dependencies": {
21 | "consolidate": "^0.12.1",
22 | "ejs": "^2.3.1",
23 | "hamljs": "^0.6.2",
24 | "handlebars": "^3.0.3",
25 | "jade": "^1.9.2",
26 | "lodash": "^3.8.0",
27 | "mustache": "^2.0.0",
28 | "nunjucks": "^1.3.4",
29 | "react": "^0.13.2",
30 | "swig": "^1.4.2"
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/ex-74-consolidate/react.js:
--------------------------------------------------------------------------------
1 | var cons = require('consolidate');
2 |
3 | cons.react('views/app.react.js', { title: 'Tim', text: 'My App' }, function(err, html) {
4 | if (err) throw err;
5 | console.log(html);
6 | });
7 |
--------------------------------------------------------------------------------
/ex-74-consolidate/swig.js:
--------------------------------------------------------------------------------
1 | var cons = require('consolidate');
2 |
3 | cons.swig('views/index.swig', { title: 'Tim', text: 'My App' }, function(err, html) {
4 | if (err) throw err;
5 | console.log(html);
6 | });
7 |
--------------------------------------------------------------------------------
/ex-74-consolidate/views/app.react.js:
--------------------------------------------------------------------------------
1 | var React = require('react');
2 |
3 | var App = React.createClass({
4 | render: function() {
5 | return (
6 | React.createElement('div', null,
7 | React.createElement('h1', null, this.props.title),
8 | React.createElement('div', {id: 'app'}, this.props.text)
9 | )
10 | );
11 | }
12 | })
13 |
14 | module.exports = App;
15 |
--------------------------------------------------------------------------------
/ex-74-consolidate/views/index.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Document
5 |
6 |
7 | <%= title %>
8 | <%= text %>
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ex-74-consolidate/views/index.haml:
--------------------------------------------------------------------------------
1 |
2 | %html
3 | %head
4 | %title Document
5 | %body
6 | %h1= title
7 | #app= text
8 |
9 |
--------------------------------------------------------------------------------
/ex-74-consolidate/views/index.hbs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Document
5 |
6 |
7 | {{ title }}
8 | {{ text }}
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ex-74-consolidate/views/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Document
5 |
6 |
7 | {{ title }}
8 | {{ text }}
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ex-74-consolidate/views/index.jade:
--------------------------------------------------------------------------------
1 | doctype html
2 | html
3 | head
4 | title Document
5 | body
6 | h1= title
7 | #app= text
8 |
--------------------------------------------------------------------------------
/ex-74-consolidate/views/index.lodash:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Document
5 |
6 |
7 | <%= title %>
8 | <%= text %>
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ex-74-consolidate/views/index.mustache:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Document
5 |
6 |
7 | {{ title }}
8 | {{ text }}
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ex-74-consolidate/views/index.swig:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Document
5 |
6 |
7 | {{ title }}
8 | {{ text }}
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ex-75-d3-to-png/.gitignore:
--------------------------------------------------------------------------------
1 | output.png
2 |
--------------------------------------------------------------------------------
/ex-75-d3-to-png/README.md:
--------------------------------------------------------------------------------
1 | node-casvas [Install Guide](https://github.com/Automattic/node-canvas/wiki/Installation---OSX)
2 |
3 | If you have some problem with below error:
4 |
5 | ```
6 | ../src/FontFace.cc:9:10: fatal error: 'fontconfig/fontconfig.h' file not found
7 | ```
8 |
9 | See issue [#528](https://github.com/Automattic/node-canvas/issues/528)
10 |
--------------------------------------------------------------------------------
/ex-75-d3-to-png/app.js:
--------------------------------------------------------------------------------
1 | var jsdom = require('jsdom');
2 | var canvg = require('canvg');
3 | var fs = require('fs');
4 |
5 | jsdom.env(
6 | '',
7 | [ 'http://d3js.org/d3.v3.min.js' ],
8 | function (err, window) {
9 |
10 | var width = 960,
11 | height = 500;
12 |
13 | var vertices = window.d3.range(100).map(function(d) {
14 | return [Math.random() * width, Math.random() * height];
15 | });
16 |
17 | var voronoi = window.d3.geom.voronoi()
18 | .clipExtent([[0, 0], [width, height]]);
19 |
20 | var svg = window.d3.select('body').append('svg')
21 | .attr('width', width)
22 | .attr('height', height)
23 | .on('mousemove', function() { vertices[0] = window.d3.mouse(this); redraw(); });
24 |
25 | var path = svg.append('g').selectAll('path');
26 |
27 | svg.selectAll('circle')
28 | .data(vertices.slice(1))
29 | .enter().append('circle')
30 | .attr('transform', function(d) { return 'translate(' + d + ')'; })
31 | .attr('r', 1.5);
32 |
33 | redraw();
34 |
35 | function redraw() {
36 | path = path
37 | .data(voronoi(vertices), polygon);
38 |
39 | path.exit().remove();
40 |
41 | path.enter().append('path')
42 | .attr('class', function(d, i) { return 'q' + (i % 9) + '-9'; })
43 | .attr('d', polygon);
44 |
45 | path.order();
46 |
47 | window.d3.selectAll('path').style('stroke', '#fff');
48 | window.d3.selectAll('path:first-child').style('fill', 'yellow !important');
49 | window.d3.selectAll('circle').style({
50 | 'fill': '#000'
51 | });
52 |
53 | window.d3.selectAll('.q0-9').style('fill', 'rgb(197,27,125)');
54 | window.d3.selectAll('.q1-9').style('fill', 'rgb(222,119,174)');
55 | window.d3.selectAll('.q2-9').style('fill', 'rgb(241,182,218)');
56 | window.d3.selectAll('.q3-9').style('fill', 'rgb(253,224,239)');
57 | window.d3.selectAll('.q4-9').style('fill', 'rgb(247,247,247)');
58 | window.d3.selectAll('.q5-9').style('fill', 'rgb(230,245,208)');
59 | window.d3.selectAll('.q6-9').style('fill', 'rgb(184,225,134)');
60 | window.d3.selectAll('.q7-9').style('fill', 'rgb(127,188,65)');
61 | window.d3.selectAll('.q8-9').style('fill', 'rgb(77,146,33)');
62 |
63 |
64 | var cvs = window.document.querySelector('body').appendChild(window.document.createElement('canvas'));
65 | var svg = window.document.querySelector('svg');
66 |
67 | console.log('svgHTML:\n', svg.outerHTML);
68 |
69 | canvg(cvs, svg.outerHTML);
70 | var imgBase64 = cvs.toDataURL().replace(/^[^,]+,/, '');
71 |
72 | console.log('toDataURL:\n', cvs.toDataURL());
73 |
74 | fs.writeFileSync('output.png', new Buffer(imgBase64, 'base64'));
75 | }
76 |
77 | function polygon(d) {
78 | return 'M' + d.join('L') + 'Z';
79 | }
80 |
81 | }
82 | );
83 |
--------------------------------------------------------------------------------
/ex-75-d3-to-png/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-75-d3-to-png",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "canvas": "^1.2.2",
14 | "canvg": "0.0.8",
15 | "d3": "^3.5.5",
16 | "jsdom": "^3.1.2"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ex-76-nodemailer-mailgun/.gitignore:
--------------------------------------------------------------------------------
1 | config.json
2 |
--------------------------------------------------------------------------------
/ex-76-nodemailer-mailgun/README.md:
--------------------------------------------------------------------------------
1 | Sign up at [Mailgun](https://mailgun.com)
2 |
3 | > 10000/month free email transport
4 |
5 | ![][http://imgur.com/xsgD6xC]
6 |
7 | Domain Information
8 |
9 | - Default SMTP Login
10 | - Default Password
11 |
12 |
13 | Write to `config.json`
14 |
15 | ```json
16 | {
17 | "user": "postmaster@sandboxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.mailgun.org",
18 | "pass": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
19 | }
20 | ```
21 |
22 | `user` should fill with ``
23 |
24 | `pass` should fill with ``
25 |
26 |
27 |
28 |
29 | See [nodemailer-wellknown](https://github.com/andris9/nodemailer-wellknown#supported-services) to know services supported by nodemailer.
30 |
--------------------------------------------------------------------------------
/ex-76-nodemailer-mailgun/app.js:
--------------------------------------------------------------------------------
1 | var nodemailer= require('nodemailer');
2 | var to = process.argv[2];
3 | var config = require('./config.json');
4 | var transport = require('nodemailer-smtp-transport');
5 |
6 | var transporter = nodemailer.createTransport(transport({
7 | service: 'Mailgun',
8 | auth: config
9 | }));
10 |
11 | var mailOptions = {
12 | from: 'Fred Foo ✔ ', // sender address
13 | to: to, // list of receivers
14 | subject: 'Hello ✔', // Subject line
15 | html: 'Hello world ✔' // html body
16 | };
17 |
18 | // send mail with defined transport object
19 | transporter.sendMail(mailOptions, function(err, info) {
20 | if (err) {
21 | console.log(err);
22 | } else {
23 | console.log('Message sent: ' + info.response);
24 | }
25 | });
26 |
--------------------------------------------------------------------------------
/ex-76-nodemailer-mailgun/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-76-nodemailer-mailgun",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "nodemailer": "^1.3.4",
13 | "nodemailer-smtp-transport": "^1.0.2"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-77-benchmark/app.js:
--------------------------------------------------------------------------------
1 | var Benchmark = require('benchmark');
2 | var lodash = require('lodash');
3 | var underscore = require('underscore');
4 | var suite = new Benchmark.Suite;
5 |
6 | var arr = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
7 |
8 | // add tests
9 | suite
10 | .add('for', function() {
11 | for (var i = 0, len = arr.length; i < len; i++) {
12 | arr[i];
13 | }
14 | })
15 | .add('Array#forEach', function() {
16 | arr.forEach(function(el) {
17 | el
18 | });
19 | })
20 | .add('underscore#each', function() {
21 | underscore.each(arr, function(el) {
22 | el
23 | });
24 | })
25 | .add('lodash#each', function() {
26 | lodash.each(arr, function(el) {
27 | el
28 | });
29 | })
30 | // add listeners
31 | .on('cycle', function(event) {
32 | console.log(String(event.target));
33 | })
34 | .on('complete', function() {
35 | console.log('Fastest is ' + this.filter('fastest').pluck('name'));
36 | })
37 | // run async
38 | .run({ 'async': true });
39 |
--------------------------------------------------------------------------------
/ex-77-benchmark/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-77-benchmark",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "benchmark": "^1.0.0",
14 | "lodash": "^3.8.0",
15 | "underscore": "^1.8.3"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ex-78-redis/2-clients.js:
--------------------------------------------------------------------------------
1 | var redis = require('redis');
2 | var client1 = redis.createClient();
3 | var client2 = redis.createClient();
4 | var msgCount = 0;
5 |
6 | client1.on('subscribe', function (channel, count) {
7 | client2.publish('a nice channel', 'I am sending a message.');
8 | client2.publish('a nice channel', 'I am sending a second message.');
9 | client2.publish('a nice channel', 'I am sending my last message.');
10 | });
11 |
12 | client1.on('message', function (channel, message) {
13 | console.log('client1 channel ' + channel + ': ' + message);
14 | msgCount += 1;
15 | if (msgCount === 3) {
16 | client1.unsubscribe();
17 | client1.end();
18 | client2.end();
19 | }
20 | });
21 |
22 | client1.incr('did a thing');
23 | client1.subscribe('a nice channel');
24 |
--------------------------------------------------------------------------------
/ex-78-redis/app.js:
--------------------------------------------------------------------------------
1 | var redis = require('redis');
2 | var client = redis.createClient();
3 |
4 |
5 | client.on('error', function (err) {
6 | console.log('Error ' + err);
7 | });
8 |
9 | client.set('string key', 'string val', redis.print);
10 |
11 | client.hset('hash key', 'hashtest 1', 'some value', redis.print);
12 |
13 | client.hset([ 'hash key', 'hashtest 2', 'some other value' ], redis.print);
14 |
15 | client.hkeys('hash key', function (err, replies) {
16 |
17 | console.log(replies.length + ' replies:');
18 |
19 | replies.forEach(function (reply, i) {
20 | console.log(' ' + i + ': ' + reply);
21 | });
22 |
23 | client.quit();
24 | });
25 |
--------------------------------------------------------------------------------
/ex-78-redis/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-78-redis",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "2-clients": "node 2-clients",
9 | "test": "echo \"Error: no test specified\" && exit 1"
10 | },
11 | "author": "",
12 | "license": "ISC",
13 | "dependencies": {
14 | "hiredis": "^0.3.0",
15 | "redis": "^0.12.1"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ex-79-umd/.gitignore:
--------------------------------------------------------------------------------
1 | app-umd.js
2 |
--------------------------------------------------------------------------------
/ex-79-umd/README.md:
--------------------------------------------------------------------------------
1 | See [umd (Universal Module Definition)](https://github.com/umdjs/umd)
2 |
3 | To write module supports `AMD`, `CommonJS`, `Global` at the same time
4 |
5 | Code Look like:
6 |
7 | ```js
8 | (function (root, factory) {
9 | if (typeof define === "function" && define.amd) {
10 | define(["jquery", "underscore"], factory);
11 | } else if (typeof exports === "object") {
12 | module.exports = factory(require("jquery"), require("underscore"));
13 | } else {
14 | root.App = factory(root.$, root._);
15 | }
16 | }(this, function ($, _) {
17 |
18 | // module implementation
19 |
20 | var App = { // ... };
21 |
22 | return App;
23 | }));
24 | ```
25 |
26 | Use browserify `--standalone` to build standalone `umd` module
27 |
28 | ```bash
29 | npm install -g browserify
30 |
31 | browserify app.js --standalone app > app-umd.js
32 | ```
33 |
--------------------------------------------------------------------------------
/ex-79-umd/app.js:
--------------------------------------------------------------------------------
1 | var SubApp = require('./subapp');
2 |
3 | var app = new SubApp();
4 |
5 | module.exports = app;
6 |
--------------------------------------------------------------------------------
/ex-79-umd/subapp.js:
--------------------------------------------------------------------------------
1 | module.exports = SubApp;
2 |
3 |
4 | function SubApp() {
5 |
6 | }
7 |
--------------------------------------------------------------------------------
/ex-80-promise-to-native/bluebird.js:
--------------------------------------------------------------------------------
1 | var Promise = require('native-or-bluebird');
2 |
3 | new Promise(function(resolve, reject) {
4 | if (Math.random() > 0.5) {
5 | resolve('success');
6 | } else {
7 | reject(new Error('failed'));
8 | }
9 | })
10 | .then(
11 | function(msg) {
12 | console.log(msg);
13 | },
14 | function(err) {
15 | console.log(err.message);
16 | }
17 | );
18 |
--------------------------------------------------------------------------------
/ex-80-promise-to-native/es6.js:
--------------------------------------------------------------------------------
1 | require('es6-promise').polyfill();
2 |
3 | new Promise(function(resolve, reject) {
4 | if (Math.random() > 0.5) {
5 | resolve('success');
6 | } else {
7 | reject(new Error('failed'));
8 | }
9 | })
10 | .then(
11 | function(msg) {
12 | console.log(msg);
13 | },
14 | function(err) {
15 | console.log(err.message);
16 | }
17 | );
18 |
--------------------------------------------------------------------------------
/ex-80-promise-to-native/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-80-promise-to-native",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "bluebird.js",
6 | "scripts": {
7 | "es6": "node es6.js",
8 | "bluebird": "node bluebird.js",
9 | "test": "echo \"Error: no test specified\" && exit 1"
10 | },
11 | "author": "",
12 | "license": "ISC",
13 | "dependencies": {
14 | "bluebird": "^2.9.25",
15 | "es6-promise": "^2.1.1",
16 | "native-or-bluebird": "^1.2.0"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ex-81-event-emitter/app.js:
--------------------------------------------------------------------------------
1 | var EventEmitter = require('events').EventEmitter;
2 | var inherits = require('util').inherits;
3 |
4 | inherits(Peer, EventEmitter);
5 |
6 | var peer1 = new Peer();
7 | var peer2 = new Peer();
8 |
9 | peer1.on('message', function(msg) {
10 | peer2.emit('message', msg);
11 | });
12 |
13 | peer2.on('message', function(msg) {
14 | console.log('message:\n', msg);
15 | });
16 |
17 | peer1.emit('message', 'Yooooooo');
18 |
19 | function Peer() {
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/ex-81-event-emitter/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-81-event-emitter",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC"
12 | }
13 |
--------------------------------------------------------------------------------
/ex-82-build-express-middleeare/app.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var app = express();
3 |
4 |
5 | app.use(require('./req-decorator')({ count: 5 }));
6 | app.use(require('./res-decorator')({ name: 'Roth' }));
7 |
8 |
9 | app.use(function(req, res) {
10 | res.send('count: ' + req.query.count);
11 | });
12 |
13 | app.listen(3000);
14 |
--------------------------------------------------------------------------------
/ex-82-build-express-middleeare/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-82-build-express-middleeare",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "req-decorator.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.12.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-82-build-express-middleeare/req-decorator.js:
--------------------------------------------------------------------------------
1 | // req decorator
2 |
3 | module.exports = function(opts) {
4 | opts = opts || {};
5 | opts.count = opts.count || 1;
6 | return function(req, res, next) {
7 | if (req.query.count) {
8 | req.query.count = (+req.query.count) + opts.count;
9 | } else {
10 | req.query.count = opts.count;
11 | }
12 | next();
13 | };
14 | };
15 |
--------------------------------------------------------------------------------
/ex-82-build-express-middleeare/res-decorator.js:
--------------------------------------------------------------------------------
1 | // res decorator
2 |
3 | module.exports = function(opts) {
4 | opts = opts || {};
5 | opts.name = opts.name || 'Tim';
6 | return function(req, res, next) {
7 | var _send = res.send.bind(res);
8 | res.send = function(text) {
9 | _send(text + ' ' + opts.name);
10 | };
11 | next();
12 | };
13 | };
14 |
--------------------------------------------------------------------------------
/ex-83-build-koa-middleeare/app.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var app = koa();
3 |
4 |
5 | app.use(require('./req-decorator')({ count: 5 }));
6 | app.use(require('./res-decorator')({ name: 'Roth' }));
7 |
8 |
9 | app.use(function *() {
10 | this.body = 'count: ' + this.count;
11 | });
12 |
13 |
14 | app.listen(3000);
15 |
--------------------------------------------------------------------------------
/ex-83-build-koa-middleeare/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-83-build-koa-middleeare",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node --harmony-generators app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "koa": "^0.20.0"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-83-build-koa-middleeare/req-decorator.js:
--------------------------------------------------------------------------------
1 | // req decorator
2 |
3 | module.exports = function(opts) {
4 | opts = opts || {};
5 | opts.count = opts.count || 1;
6 | return function *(next) {
7 | if (this.query.count) {
8 | this.count = (+this.query.count) + opts.count;
9 | } else {
10 | this.count = opts.count;
11 | }
12 | yield next;
13 | };
14 | };
15 |
--------------------------------------------------------------------------------
/ex-83-build-koa-middleeare/res-decorator.js:
--------------------------------------------------------------------------------
1 | // res decorator
2 |
3 | module.exports = function(opts) {
4 | opts = opts || {};
5 | opts.name = opts.name || 'Tim';
6 | return function *(next) {
7 | yield next;
8 | this.body = this.body + ' ' + opts.name;
9 | };
10 | };
11 |
--------------------------------------------------------------------------------
/ex-84-exec-bash/app.js:
--------------------------------------------------------------------------------
1 | var exec = require('child_process').exec;
2 |
3 | exec('pwd', puts);
4 |
5 | exec('ls -la', puts);
6 |
7 |
8 | function puts(err, stdout, stderr) {
9 | console.log(stdout);
10 | console.log(stderr);
11 | if (err) {
12 | console.log('exec error: ' + err);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/ex-84-exec-bash/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-84-exec-bash",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC"
12 | }
13 |
--------------------------------------------------------------------------------
/ex-85-process-fork/app.js:
--------------------------------------------------------------------------------
1 | var fork = require('child_process').fork;
2 |
3 | for(var i = 0; i < 10; i++) {
4 | var worker = fork('worker.js', [ i ]);
5 | worker.on('message', function(m) {
6 | console.log('PARENT got message:', m);
7 | });
8 | worker.send({ hello: 'world' });
9 | worker.on('close', function () {
10 | console.log('child process exited');
11 | });
12 | }
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/ex-85-process-fork/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-85-process-fork",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC"
11 | }
12 |
--------------------------------------------------------------------------------
/ex-85-process-fork/worker.js:
--------------------------------------------------------------------------------
1 |
2 | process.on('message', function(m) {
3 | console.log('CHILD got message:', m);
4 | process.kill(process.pid);
5 | });
6 |
7 | process.send({ id: process.argv[2], foo: 'bar' });
8 |
--------------------------------------------------------------------------------
/ex-86-levelup/.gitignore:
--------------------------------------------------------------------------------
1 | db
2 |
--------------------------------------------------------------------------------
/ex-86-levelup/app.js:
--------------------------------------------------------------------------------
1 | var levelup = require('levelup');
2 |
3 | // 1) Create our database, supply location and options.
4 | // This will create or open the underlying LevelDB store.
5 | var db = levelup('./db');
6 |
7 | // 2) put a key & value
8 | db.put('name', 'LevelUP', function (err) {
9 | if (err) return console.log('Ooops!', err); // some kind of I/O error
10 |
11 | // 3) fetch by key
12 | db.get('name', function (err, value) {
13 | if (err) return console.log('Ooops!', err); // likely the key was not found
14 |
15 | // ta da!
16 | console.log('name=' + value);
17 | })
18 | })
19 |
--------------------------------------------------------------------------------
/ex-86-levelup/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-86-levelup",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "leveldown": "^1.0.6",
14 | "levelup": "^1.0.0-5"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ex-87-rethinkdb/.gitignore:
--------------------------------------------------------------------------------
1 | rethinkdb_data
2 |
--------------------------------------------------------------------------------
/ex-87-rethinkdb/README.md:
--------------------------------------------------------------------------------
1 | Install [doc](http://www.rethinkdb.com/docs/install/)
2 |
3 | and then
4 |
5 | ```bash
6 | $ rethinkdb
7 | ```
8 |
9 | open `http://localhost:8080/` to see web interface.
10 |
11 | [detail](http://rethinkdb.com/docs/start-a-server/)
12 |
--------------------------------------------------------------------------------
/ex-87-rethinkdb/app.js:
--------------------------------------------------------------------------------
1 | var r = require('rethinkdb');
2 |
3 | var CONFIG = { host: 'localhost', port: 28015 }
4 |
5 | var _conn;
6 |
7 | r.connect(CONFIG)
8 | .then(
9 | function(conn) {
10 | _conn = conn;
11 | return r.db('test').tableCreate('tv_shows').run(_conn);
12 | },
13 | throwError
14 | )
15 | .then(
16 | function(res) {
17 | console.log(res);
18 | return r.table('tv_shows').insert({ name: 'Star Trek TNG' }).run(_conn);
19 | },
20 | throwError
21 | )
22 | .then(console.log, throwError);
23 |
24 | function throwError(err) { throw err; }
25 |
--------------------------------------------------------------------------------
/ex-87-rethinkdb/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-87-rethinkdb",
3 | "version": "1.0.0",
4 | "description": "Install [doc](http://www.rethinkdb.com/docs/install/)",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "rethinkdb": "^2.0.0"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-88-email-template/.gitignore:
--------------------------------------------------------------------------------
1 | config.json
2 |
--------------------------------------------------------------------------------
/ex-88-email-template/README.md:
--------------------------------------------------------------------------------
1 | Prerequisite ex-76
2 |
--------------------------------------------------------------------------------
/ex-88-email-template/app.js:
--------------------------------------------------------------------------------
1 | var nodemailer= require('nodemailer');
2 | var to = process.argv[2];
3 | var path = require('path');
4 | var config = require('./config.json');
5 | var transport = require('nodemailer-smtp-transport');
6 | var templatesDir = path.resolve(__dirname, '.', 'templates');
7 | var emailTemplates = require('email-templates');
8 |
9 | emailTemplates(templatesDir, function(err, template) {
10 | if (err) console.log(err);
11 | else {
12 | var transporter = nodemailer.createTransport(transport({
13 | service: 'Mailgun',
14 | auth: config
15 | }));
16 |
17 | template('newsletter', { title: 'Hello', text: 'see you' }, function(err, html, text) {
18 | if (err) console.log(err);
19 | else {
20 | // send mail with defined transport object
21 | transporter.sendMail({
22 | from: 'Fred Foo ✔ ', // sender address
23 | to: to, // list of receivers
24 | subject: 'Hello ✔', // Subject line
25 | html: html,
26 | // generateTextFromHTML: true,
27 | text: text
28 | }, function(err, info) {
29 | if (err) {
30 | console.log(err);
31 | } else {
32 | console.log('Message sent: ' + info.response);
33 | }
34 | });
35 | }
36 | });
37 | }
38 | });
39 |
--------------------------------------------------------------------------------
/ex-88-email-template/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-88-email-template",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "email-templates": "^1.2.1",
13 | "jade": "^1.9.2",
14 | "nodemailer": "^1.3.4",
15 | "nodemailer-smtp-transport": "^1.0.2",
16 | "stylus": "^0.51.1"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ex-88-email-template/templates/newsletter/html.jade:
--------------------------------------------------------------------------------
1 | doctype html
2 | html
3 | head
4 | title Document
5 | body
6 | h1= title
7 | #app= text
8 |
--------------------------------------------------------------------------------
/ex-88-email-template/templates/newsletter/style.stylus:
--------------------------------------------------------------------------------
1 | h1
2 | color blue
3 |
--------------------------------------------------------------------------------
/ex-88-email-template/templates/newsletter/text.jade:
--------------------------------------------------------------------------------
1 | Yaaaaaaaa
2 |
--------------------------------------------------------------------------------
/ex-89-json-server/README.md:
--------------------------------------------------------------------------------
1 |
2 | ```bash
3 | npm start
4 | ```
5 |
6 | ```
7 | http://localhost:3000/posts
8 | http://localhost:3000/posts/1
9 | http://localhost:3000/users
10 | http://localhost:3000/users/1
11 | http://localhost:3000/comments
12 | http://localhost:3000/comments/1
13 | ```
14 |
15 |
16 |
17 | Based on the previous db.json, here are all the available routes.
18 |
19 | ```
20 | GET /posts
21 | GET /posts/1
22 | GET /posts/1/comments
23 | GET /posts?title=json-server&author=typicode
24 | POST /posts
25 | PUT /posts/1
26 | PATCH /posts/1
27 | DEL /posts/1
28 | ```
29 |
30 | To slice resources, add _start and _end or _limit. An X-Total-Count header is included in the response.
31 |
32 | ```
33 | GET /posts?_start=20&_end=30
34 | GET /posts?_start=20&_limit=10
35 | GET /posts/1/comments?_start=20&_end=30
36 | ```
37 |
38 |
39 |
40 | Enter `s` can create a snapshot of the db.
41 |
--------------------------------------------------------------------------------
/ex-89-json-server/db.json:
--------------------------------------------------------------------------------
1 | {
2 | "posts": [
3 | {
4 | "id": 1,
5 | "title": "json-server",
6 | "author": "typicode"
7 | }
8 | ],
9 | "comments": [
10 | {
11 | "id": 1,
12 | "body": "some comment",
13 | "postId": 1
14 | }
15 | ],
16 | "users": [
17 | {
18 | "id": 1,
19 | "name": "Tim",
20 | "isMale": true
21 | },
22 | {
23 | "id": 2,
24 | "name": "Roth",
25 | "isMale": true
26 | }
27 | ]
28 | }
--------------------------------------------------------------------------------
/ex-89-json-server/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-89-json-server",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "json-server db.json",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "json-server": "^0.7.4"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ex-90-dns/app.js:
--------------------------------------------------------------------------------
1 | var dns = require('dns');
2 | dns.resolve4('www.google.com', console.log);
3 |
4 | // log ip
5 |
--------------------------------------------------------------------------------
/ex-90-dns/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ex-90-dns",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "start": "node app.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC"
12 | }
13 |
--------------------------------------------------------------------------------
/exercises/coo.js:
--------------------------------------------------------------------------------
1 | var co = require('co');
2 | var http = require('http');
3 | var Promise = require('bluebird');
4 | var readFile = Promise.promisify(require('fs').readFile);
5 |
6 |
7 | http.createServer(function(request, response) {
8 | response.writeHead(200, {'Content-Type':'text/plain'});
9 |
10 | co(function *() {
11 | var text = yield readFile(__dirname + '/hello.txt');
12 | response.write(text + ' Tim!');
13 | response.end();
14 | });
15 |
16 | }).listen(3000);
17 |
18 |
19 | /* ES7
20 | async function *() {
21 | var text = await readFile(__dirname + '/hello.txt');
22 | response.write(text);
23 | response.end();
24 | }
25 | */
--------------------------------------------------------------------------------
/exercises/hello.txt:
--------------------------------------------------------------------------------
1 | Hello World!
--------------------------------------------------------------------------------
/exercises/koaa.js:
--------------------------------------------------------------------------------
1 | var koa = require('koa');
2 | var app = koa();
3 | var Promise = require('bluebird');
4 | var readFile = Promise.promisify(require('fs').readFile);
5 |
6 |
7 | app.use(function *(next) {
8 | var text = yield readFile(__dirname + '/hello.txt');
9 | this.body = text + ' Tim!';
10 | yield next;
11 | this.body += ' Deyu!';
12 | });
13 |
14 | app.use(function *(next) {
15 | this.body += ' Roth!';
16 | try {
17 | yield next;
18 | } catch (e) {
19 | console.log('TIM');
20 | }
21 |
22 | });
23 |
24 | app.use(function *() {
25 | throw new Error('boooom');
26 | this.body += ' Roth2!';
27 | });
28 |
29 |
30 | app.listen(3000);
31 |
--------------------------------------------------------------------------------
/exercises/promisee.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 | var Promise = require('bluebird');
3 | var readFile = Promise.promisify(require('fs').readFile);
4 |
5 |
6 | http.createServer(function(request, response) {
7 | response.writeHead(200, {'Content-Type':'text/plain'});
8 |
9 | readFile(__dirname + '/hello.txt')
10 | .then(function(text) {
11 | response.write(text);
12 | response.end();
13 | });
14 |
15 | }).listen(3000);
16 |
17 |
18 | /*
19 | new Promise(function(resolve, reject) {});
20 | Promise.a = function(){...};
21 | */
--------------------------------------------------------------------------------
/exercises/server.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 | var fs = require('fs');
3 |
4 |
5 | http.createServer(function(request, response) {
6 | response.writeHead(200, {'Content-Type':'text/plain'});
7 |
8 | fs.readFile(__dirname + '/hello.txt', function(err, text) {
9 | response.write(text);
10 | response.end();
11 | });
12 |
13 | }).listen(3000);
14 |
--------------------------------------------------------------------------------
/exx-01-electron/README.md:
--------------------------------------------------------------------------------
1 | 需要依照不同 os 安裝不同程式執行
2 |
3 | https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md#run-your-app
4 |
--------------------------------------------------------------------------------
/exx-01-electron/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Hello World!
5 |
15 |
16 |
17 | Hello Electron!
18 |
19 |
20 |
--------------------------------------------------------------------------------
/exx-01-electron/main.js:
--------------------------------------------------------------------------------
1 | var app = require('app');
2 | var BrowserWindow = require('browser-window');
3 |
4 | require('crash-reporter').start();
5 |
6 | var mainWindow = null;
7 |
8 | app.on('window-all-closed', function() {
9 | if (process.platform != 'darwin')
10 | app.quit();
11 | });
12 |
13 |
14 | app.on('ready', function() {
15 |
16 | mainWindow = new BrowserWindow({width: 800, height: 600});
17 |
18 | mainWindow.loadUrl('file://' + __dirname + '/index.html');
19 |
20 | mainWindow.on('closed', function() {
21 | mainWindow = null;
22 | });
23 |
24 | });
25 |
--------------------------------------------------------------------------------
/exx-01-electron/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "exx-01-electron",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "main.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC"
11 | }
12 |
--------------------------------------------------------------------------------
/exx-02-ajax/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Github User Search
5 |
21 |
22 |
23 | Github User Search
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/exx-02-ajax/index.js:
--------------------------------------------------------------------------------
1 | var request = require('superagent');
2 | var cheerio = require('cheerio');
3 |
4 | var keyword = document.getElementById('keyword');
5 | var btn = document.getElementById('search-btn');
6 | var result = document.getElementById('result');
7 |
8 | btn.addEventListener('click', function() {
9 | var val = keyword.value;
10 | request
11 | .get('https://github.com/' + val)
12 | .end(function(err, res) {
13 | if (!res.ok) return;
14 | result.innerHTML = '';
15 |
16 | var $ = cheerio.load(res.text);
17 |
18 | var fullname = $('.vcard-fullname').text();
19 | var username = $('.vcard-username').text();
20 | var avatar = $('.avatar').attr('src');
21 | var counts = $('.vcard-stats').find('.vcard-stat-count');
22 | var followers = counts.eq(0).text();
23 | var starred = counts.eq(1).text();
24 | var following = counts.eq(2).text();
25 |
26 | console.log(fullname, username, avatar, followers, starred, following);
27 |
28 | var title = document.createElement('h2');
29 | title.innerHTML += fullname;
30 |
31 | var subtitle = document.createElement('h4');
32 | subtitle.innerHTML += username;
33 | subtitle.style.color = 'gray';
34 |
35 | var image = document.createElement('img');
36 | image.src = avatar;
37 |
38 | var fer = document.createElement('p');
39 | fer.innerHTML += 'followers: ';
40 | fer.innerHTML += followers;
41 | fer.style.color = 'red';
42 |
43 | var sta = document.createElement('p');
44 | sta.innerHTML += 'starred: ';
45 | sta.innerHTML += starred;
46 | sta.style.color = 'green';
47 |
48 | var fing = document.createElement('p');
49 | fing.innerHTML += 'followers: ';
50 | fing.innerHTML += followers;
51 | fing.style.color = 'blue';
52 |
53 | result.appendChild(title);
54 | result.appendChild(subtitle);
55 | result.appendChild(image);
56 | result.appendChild(fer);
57 | result.appendChild(sta);
58 | result.appendChild(fing);
59 |
60 | });
61 |
62 | });
63 |
--------------------------------------------------------------------------------
/exx-02-ajax/main.js:
--------------------------------------------------------------------------------
1 | var app = require('app');
2 | var BrowserWindow = require('browser-window');
3 |
4 | require('crash-reporter').start();
5 |
6 | var mainWindow = null;
7 |
8 | app.on('window-all-closed', function() {
9 | if (process.platform != 'darwin')
10 | app.quit();
11 | });
12 |
13 |
14 | app.on('ready', function() {
15 |
16 | mainWindow = new BrowserWindow({width: 800, height: 600});
17 |
18 | mainWindow.loadUrl('file://' + __dirname + '/index.html');
19 |
20 | mainWindow.on('closed', function() {
21 | mainWindow = null;
22 | });
23 |
24 | mainWindow.openDevTools();
25 |
26 | });
27 |
--------------------------------------------------------------------------------
/exx-02-ajax/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "exx-02-electron",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "main.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "cheerio": "^0.19.0",
13 | "superagent": "^1.2.0"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/exx-03-d3/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | D3
5 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/exx-03-d3/index.js:
--------------------------------------------------------------------------------
1 | var d3 = require('d3');
2 | var _ = require('lodash');
3 |
4 | var width = 800;
5 | var height = 600;
6 |
7 | var length = Math.random() * 50;
8 |
9 | var dataset = _.map(_.range(50), function (i) {
10 | return Math.random() * 500;
11 | });
12 |
13 | var svg = d3.selectAll('.svg');
14 |
15 | // var colorScale = d3.scale.linear()
16 | // .domain([0, dataset.length])
17 | // .range([ 'yellow', 'red' ]);
18 | //
19 | var colorScale = d3.scale.category20c()
20 |
21 | var divs = svg.selectAll('div')
22 | .data(dataset)
23 | .enter().append('div')
24 | .style({
25 | 'color': 'white',
26 | 'display': 'inline-block',
27 | 'width': function(d, i) {
28 | return (width / dataset.length) + 'px';
29 | },
30 | 'height': function(d, i) {
31 | return (d) + 'px';
32 | }
33 | })
34 | .style('background-color', function(d, i) {
35 | return d3.hsl((360 / dataset.length) * (i + 1), 1, 0.6);
36 | })
37 |
--------------------------------------------------------------------------------
/exx-03-d3/main.js:
--------------------------------------------------------------------------------
1 | var app = require('app');
2 | var BrowserWindow = require('browser-window');
3 |
4 | require('crash-reporter').start();
5 |
6 | var mainWindow = null;
7 |
8 | app.on('window-all-closed', function() {
9 | if (process.platform != 'darwin')
10 | app.quit();
11 | });
12 |
13 |
14 | app.on('ready', function() {
15 |
16 | mainWindow = new BrowserWindow({width: 800, height: 600});
17 |
18 | mainWindow.loadUrl('file://' + __dirname + '/index.html');
19 |
20 | mainWindow.on('closed', function() {
21 | mainWindow = null;
22 | });
23 |
24 | // mainWindow.openDevTools();
25 |
26 | });
27 |
--------------------------------------------------------------------------------
/exx-03-d3/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "exx-03-d3",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "main.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "d3": "^3.5.5",
13 | "lodash": "^3.8.0"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/exx-04-cool-face/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Cool Face
5 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/exx-04-cool-face/index.js:
--------------------------------------------------------------------------------
1 | var cool = require('cool-ascii-faces');
2 | var face = document.getElementById('face');
3 |
4 | setTimeout(function changeFace() {
5 | face.innerHTML = cool();
6 | setTimeout(changeFace, 2000);
7 | }, 2000);
8 |
9 |
--------------------------------------------------------------------------------
/exx-04-cool-face/main.js:
--------------------------------------------------------------------------------
1 | var app = require('app');
2 | var BrowserWindow = require('browser-window');
3 |
4 | require('crash-reporter').start();
5 |
6 | var mainWindow = null;
7 |
8 | app.on('window-all-closed', function() {
9 | if (process.platform != 'darwin')
10 | app.quit();
11 | });
12 |
13 |
14 | app.on('ready', function() {
15 |
16 | mainWindow = new BrowserWindow({width: 800, height: 600});
17 |
18 | mainWindow.loadUrl('file://' + __dirname + '/index.html');
19 |
20 | mainWindow.on('closed', function() {
21 | mainWindow = null;
22 | });
23 |
24 | });
25 |
--------------------------------------------------------------------------------
/exx-04-cool-face/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "exx-04-cool-face",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "main.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "cool-ascii-faces": "^1.3.3"
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "startLearningNodejs",
3 | "version": "1.0.0",
4 | "description": "test from website: http://www.nodebeginner.org/",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "test-travis": "node node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha ex-67-travis-ci/test --report lcovonly"
9 | },
10 | "repository": {
11 | "type": "git",
12 | "url": "https://github.com/chentsulin/startLearningNodejs.git"
13 | },
14 | "author": "",
15 | "license": "ISC",
16 | "bugs": {
17 | "url": "https://github.com/chentsulin/startLearningNodejs/issues"
18 | },
19 | "homepage": "https://github.com/chentsulin/startLearningNodejs",
20 | "devDependencies": {
21 | "chai": "^2.3.0",
22 | "istanbul": "^0.3.13",
23 | "mocha": "^2.2.4"
24 | },
25 | "dependencies": {
26 | "bluebird": "^2.9.25",
27 | "consolidate": "^0.12.1",
28 | "ejs": "^2.3.1",
29 | "es6-promise": "^2.1.1",
30 | "haml": "^0.4.3",
31 | "hamljs": "^0.6.2",
32 | "jade": "^1.9.2",
33 | "koa": "^0.20.0",
34 | "native-or-bluebird": "^1.2.0",
35 | "nodemailer": "^1.3.4",
36 | "simple-peer": "^5.4.3",
37 | "wrtc": "0.0.55"
38 | }
39 | }
40 |
--------------------------------------------------------------------------------