Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.
-
It is better to start using nvm, the Node Version Manager. E.g.
nvm install 4.4
-
Node.js 'hello world' in
src/ch1/hello-world.js
. -
Using
npm init
to generate thepackage.json
, ornpm init --yes
-
Modularization of your application:
|-- app | |-- calc.js | |__ index.js | |--- index.js |___ package.json
-
Keeping your root
index.js
simple, like:// index.js require('./app/index.js');
-
Start building the actual application in
app/index.js
-
Finish the actual business logic in
app/calc.js
-
Visit the NPM website at https://npmjs.com, and sign up your account.
-
Make sure you install npm v3, or you can
npm install npm@3 -g
-
Adding dependencies:
npm install lodash --save
or build-time dependenciesnpm install babel --save-dev
-
After
npm install
, it is better tonpm dedupe
-
Using NPM scripts:
"script": { "start": "node index.js", "test" "mocha test", "your-custom-script": "echno npm" }
-
Run your NPM scripts, via
npm start
, ornpm run test
-
Using scoped/private packages:
- naming pattern:
@myorg/mypackage
- install:
npm install @myorg/mypackage --save
- requiring:
require('myorg/mypackage');
- naming pattern:
- Getting started with NPM
- AlloyTeam: Master NPM
dependencies
vsdevDependencies
- Taobao NPM
- Semantic version: Major.Mionor.Patch
Asynchronous I/O is a form of input/output processing that permits other processing to continue before the transmission has finished.
- Read file sync:
fs.readFileSync('file.md', 'utf-8')
- Using error-first callbacks: pass a function to another function as a parameter, you can call it within the function when you are
finished with your job. (no return value)
- error-handing: instead of a
try-catch
block you have to check for errors in the callback - no return value: async functions don't return values, but values will be passed to the callbacks
- error-handing: instead of a
- Meet the event loop, which is the heart of Node.js/JavaScript - if is responsible for scheduling asynchronous operations.
- Async control flow, which is a way to organize your codes.
- Opt 1: async.js
- Opt 2: Promises - the Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet but is expected in the future.
- See Promise codes in
src/ch3/file-async-promise.js
- Getting to know
http
andhttps
module, see docs - Writing a simple server:
src/ch4/server.js
- The
http
module is very low-level, there are a lot of advanced frameworks to pick: - Getting started with Express:
src/ch4/express-server.js
- By default, Express gives you a router. see API docs
- Express app routing:
app.get
,app.post
,app.put
- Getting to know middlewares (as Unix pipelines, but for HTTP requests):
- Define Express middleware:
app.use((req, res, next) => { do something })
- Error handling in Express: using a special middleware function
- it should be the last middleware added with
app.use
- it should be the last middleware added with
- Define Express middleware:
- Rendering HTML:
- using handlebars package with the express-handlebars wrapper.
- checking express-handlebars docs
- Debugging Express:
- Pass the environment variable to Express:
DEBUG=express*
, like$ DEBUG=express* node index.js
- Pass the environment variable to Express:
- Storing data in a global variable - in memory for the lifetime of your app.
- RAM is expensive
- when app restart, all data will lost
- stack overflow
- Storing data in a file
- hard to updating or deleting
- hard in parallel
- hard to scale up your app
- SQL - relational databases
- NoSQL - Not only SQL
- Node.js and MongoDB
- Node.js and PostgrelSQL
- Setup a PostgrelSQL database server
- Database browser tool: psql, cheat sheet
- GUI tool for PostgreSQL administration: pgAdmin
- Online course for PostgreSQL
- HTTP: Hypertext Transfer Protocol. Http functions as a request-response protocol in the client-server computing model.
- HTTP Status Codes:
- 1xx - Informational
- 2xx - Success, our request was received and processed correctly
- 200 OK
- 201 Created
- 204 No Content
- 3xx - Redirection, the client had to do additional action to complete the request.
- 301 Moved Permanently
- 304 Not Modified
- 4xx - Client Error
- 400 Bad Request
- 401 Unauthorized
- 403 Forbidden
- 404 Not Found
- 409 Conflict
- 5xx - Server Error: server failed to fulfill a valid request due to some error
- 500 Internal Server Error
- 503 Service Unavailable
- Find details here
- Sending requests to external APIs:
- Using HTTP module in Node.js
- NPM: request or superagent
- Fetch API: isomorphic-fetch
- request-promise is another option.
- Error handling: error-first callback, or
catch
in promise way
Here are some suggestions from RisingStack:
-
Organize your files around features, not roles. The problem is:
- To understand how the product pages work, you have to open up three different directories, with lots of context switching,
- you end up writing long paths when requiring modules:
require('../../controllersuser.js')
// DON'T . ├── controllers | ├── product.js | └── user.js ├── models | ├── product.js | └── user.js ├── views | ├── product.hbs | └── user.hbs // Good . ├── product | ├── index.js | ├── product.js | └── product.hbs ├── user | ├── index.js | ├── user.js | └── user.hbs
-
Don't put logic in
index.js
files- Use these
index.js
files only to export functionlity, like
// product/index.js var product = require('./product') module.exports = { create: product.create }
- Use these
-
Place your test files next to the implementation
- Using tests to checking whether a module produces the expected output
- Also using tests to document your modules
- Put your additional test files to a separate
test
folder to avoid confusion
. ├── test | └── setup.spec.js ├── product | ├── index.js | ├── product.js | ├── product.spec.js | └── product.hbs ├── user | ├── index.js | ├── user.js | ├── user.spec.js | └── user.hbs
-
Use a
config
directory to place your configuration files. ├── config | ├── index.js | └── server.js ├── product | ├── index.js | ├── product.js | ├── product.spec.js | └── product.hbs
-
Put your long npm scripts in a
scripts
directory. ├── scripts | ├── syncDb.sh | └── provision.sh ├── product | ├── index.js | ├── product.js | ├── product.spec.js | └── product.hbs