实用 Node.js

卢涛南 Randy

国际业务部 Newbee Team

基本语法

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript

常用的 ES6 特性

https://babeljs.io/learn-es2015/

变量声明

let foo = 'foo'

function a () {
  let bar = 'bar'
}

console.log(bar) // => undefined

常量声明

const foo = 'foo'

foo = 'bar' // => Error

普通函数

function foo () {
    console.log('foo...')
}

foo() // => foo...
const foo = () => {
    console.log('foo...')
}

foo() // => foo...

箭头函数

describe('a suite of tests', function() {
  this.timeout(500);
})

describe('a suite of tests', () => {
  this.timeout(500);

  // TypeError: this.timeout is not a function
})

异步

fs.readFileSync('temp.txt', 'utf8')

console.log('do other things...')

阻塞

处理异步的方式

以一个 delay 方法的实现讲解

callback

function delay (time, callback) {
  setTimeout(() => {
    callback()
  }, time)
}

delay(1000, () => {
  console.log('first delay...')
  delay(1000, () => {
    console.log('second delay...')
  })
})

Promise

function delay (time) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, time)
  })
}

delay(1000)
  .then(() => {
    console.log('first delay...')
    return delay(1000)
  })
  .then(() => {
    console.log('second delay...')
  })

Async/Await (Node 8+)

function delay (time) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, time)
  })
}

(async () => {
  await delay(1000)
  console.log('first delay...')
  await delay(1000)
  console.log('second delay...')
})()

优雅地搭建 Node.js 环境

Why not use distributions

  • 版本切换不方便
  • 不纯净

nvm

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash

https://github.com/creationix/nvm

一条命令安装

安装 Node.js

$ nvm install 8

切换版本

$ nvm use 6

模块化

require()

https://nodejs.org/api/modules.html

// lib/utils.js

exports.foo = function () {
    // ...
}

exports

// lib/index.js

const utils = require('./utils')

utils.foo()

import

// lib/index.js

const { foo } = require('./utils')

foo()
// lib/foo.js

function foo() {
    console.log('foo')
}

module.exports = foo

// lib/index.js

const foo = require('./foo')

foo()

module.exports

「包」的概念

package.json

https://docs.npmjs.com/files/package.json

/home/projects/foo.js

require('bar.js')

  • /home/projects/node_modules/bar.js
  • /home/node_modules/bar.js
  • /home/node_modules/bar.js
  • /node_modules/bar.js

npm install macaca-wd --save

const wd = require('macaca-wd')

npm

npm install macaca-cli -g

$ macaca docter

npm script

{
    "scripts": {
        "docter": "macaca doctor",
        "server": "macaca server"
    }
}

npm i macaca-cli --save

npm run server

const path = require('path')

// /home/projects/Newbee/lib/bar.js

path.resolve(__dirname, './foo.js') 

// => /home/projects/Newbee/lib/foo.js

Q&A

  1. 除了 StackOveflow, 官方 API doc 是解决问题最好的地方。
  2. 不要害怕报错信息。

实用 Node.js

By Randy Lu

实用 Node.js

  • 678
Loading comments...

More from Randy Lu