Node.js 基础

1. 安装

https://nodejs.org/

2. 概念

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时。
Node.js 使用了一个异步事件驱动的、非阻塞式 IO 的模型。

3. HelloWorld

const http = require('http')
const server = http.createServer((req, res) => {
    res.statusCode = 200
    res.writeHead('Content-Type', 'text/plain')
    res.write('Hello, world.')
    res.end()
})
server.listen(3000, '127.0.0.1', () => {
    console.log(`Server is running at [http://127.0.0.1:3000/].`)
})

4. REPL

node

5. Buffer

const buffer = Buffer.from('hello', 'ascii')
buffer.toString('hex')
buffer.toString('base64')
buffer.toJSON()
Buffer.alloc()

6. 函数

function/Function

7. callback

;((root) => {
    new Promise((resolve, reject) => {
        setTimeout(() => {
            let flag = true
            if (flag) {
                resolve('resolved')
            } else {
                reject('rejected')
            }
        }, 3000)
    })
    .then(res) {
        console.log(res)
    }
    .catch(err) {
        console.log(err)
    }
    .finish() {
        console.log('finished')
    }
})(this);

8. events

EventEmitters-emit->Events-EventLoop->EventHandlers

const events = require('events')
let eventEmitter = new events.EventEmitter()
eventEmitter.on('click', (parm1, parm2) => {
    console.log(parm1, parm2)
})
eventEmitter.emit('click', parm1, parm2)

on/once/addListener/removeListener/removeAllListeners/listeners/listenerCout/setMaxListeners/emit

9. Stream

Readable/Writable/Duplex/Transform
data/end/error/finish

10. 全局

global/__dirname/__filename/process/console/setTimeout/clearTimeout/setInterval/clearInterval

11. 模块

require/exports/module.exports

12. NPM

npm -v
npm --version
npm search npm
npm install npm -g
npm uninstall npm -g
npm update npm -g
npm list npm -g
npm init
npm config
npm publish
npm unpublish
npm help

13. url

const url = require('url')
url.parse(req.url).pathname
url.parse(req.url).query

14. util

const util = require('util')
util.callbackify(original)
util.inherits(constructor, superConstructor)
util.inspect(object, [showHidden, ][depth, ][colors])
util.isArray(object)
util.isRegExp(object)
util.isDate(object)

15. fs

const fs = require('fs')
fs.stat()
fs.readFile()
fs.readFileSync()
fs.writeFile()
fs.unlink()
fs.mkdir()
fs.readdir()
fs.rmdir()
fs.open()
fs.read()
fs.write()
fs.ftruncate()
fs.close()

16. 工具模块

os/path/net/dns/domain

17. Web 框架

Express/Koa/Koa2/Egg

18. 数据库

mysql/mongodb

你可能感兴趣的:(Node.js 基础)