Skip to content
This repository has been archived by the owner on May 23, 2022. It is now read-only.

wwsun/node-hero

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Node Hero

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.

Node.js In a Nutshell

  1. It is better to start using nvm, the Node Version Manager. E.g. nvm install 4.4

  2. Node.js 'hello world' in src/ch1/hello-world.js.

  3. Using npm init to generate the package.json, or npm init --yes

  4. Modularization of your application:

     |-- app
     |    |-- calc.js
     |    |__ index.js
     |
     |--- index.js
     |___ package.json
    
  5. Keeping your root index.js simple, like:

    // index.js
    require('./app/index.js');
  6. Start building the actual application in app/index.js

  7. Finish the actual business logic in app/calc.js

Readings

Using NPM

  1. Visit the NPM website at https://npmjs.com, and sign up your account.

  2. Make sure you install npm v3, or you can npm install npm@3 -g

  3. Adding dependencies: npm install lodash --save or build-time dependencies npm install babel --save-dev

  4. After npm install, it is better to npm dedupe

  5. Using NPM scripts:

     "script": {
         "start": "node index.js",
         "test" "mocha test",
         "your-custom-script": "echno npm"
     }
    
  6. Run your NPM scripts, via npm start, or npm run test

  7. Using scoped/private packages:

    • naming pattern: @myorg/mypackage
    • install: npm install @myorg/mypackage --save
    • requiring: require('myorg/mypackage');

Readings

Async Programming in Node.js

Asynchronous I/O is a form of input/output processing that permits other processing to continue before the transmission has finished.

  1. Read file sync: fs.readFileSync('file.md', 'utf-8')
  2. 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
  3. Meet the event loop, which is the heart of Node.js/JavaScript - if is responsible for scheduling asynchronous operations.
  4. 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

Readings

Simple Node.js Server

  1. Getting to know http and https module, see docs
  2. Writing a simple server: src/ch4/server.js
  3. The http module is very low-level, there are a lot of advanced frameworks to pick:
  4. 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
  5. 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
  6. Rendering HTML:
  7. Debugging Express:
    • Pass the environment variable to Express: DEBUG=express*, like $ DEBUG=express* node index.js

Reading

Node.js Database

  1. 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
  2. Storing data in a file
    • hard to updating or deleting
    • hard in parallel
    • hard to scale up your app
  3. SQL - relational databases
  4. NoSQL - Not only SQL
  5. Node.js and MongoDB
  6. Node.js and PostgrelSQL

Reading

Node.js Request Module

  1. HTTP: Hypertext Transfer Protocol. Http functions as a request-response protocol in the client-server computing model.
  2. 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
  3. Sending requests to external APIs:

Reading

Node.js Project Structure

Here are some suggestions from RisingStack:

  1. 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    
    
  2. 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
    }
  3. 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
    
  4. Use a config directory to place your configuration files

    .
    ├── config
    |   ├── index.js
    |   └── server.js
    ├── product
    |   ├── index.js
    |   ├── product.js
    |   ├── product.spec.js
    |   └── product.hbs
    
  5. Put your long npm scripts in a scripts directory

    .
    ├── scripts
    |   ├── syncDb.sh
    |   └── provision.sh
    ├── product
    |   ├── index.js
    |   ├── product.js
    |   ├── product.spec.js
    |   └── product.hbs
    

About

Demo codes for node.js

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published