nodejs複習05

stream

可讀流

  • fs.pause()方法會使處於流動模式的流中止觸發data事件,切換到非流動模式並讓後續數據流在內部緩衝區
var fs = require('fs')

var rs = fs.createReadStream('2.txt');

rs.setEncoding('utf8')

//當一個數據快能夠從流中被讀出觸發
rs.on('readable', function () {
    console.log('readable event');
})

//讀取數據塊時操做
rs.on('data', function (chunk) {
    console.log('data event');
    rs.pause();  //中止
    setTimeout(function () {
        rs.resume() //恢復
        console.log(chunk);
    }, 3000)
})

//數據接收發生錯誤時
rs.on('error', function (err) {
    console.log('error event');
})

//沒有更多數據可以提供時
rs.on('end', function () {
    console.log('end event');
})

//底層數據源(如數據源文件描述符)被關閉時觸發
//注意不是全部流都會觸發
rs.on('close', function () {
    console.log('close event');
})
  • 可讀流有兩種模式: 流動模式和暫停模式,暫停模式必須明確調用stream.read(size)方法,默認流動模式
  • read發明合法用語從內部緩存區中讀取並返回數據;沒有設置size則一次返回全部緩衝區數據
  • read方法僅在暫停模式時被調用,流動模式會自動調用
//暫停模式,無需再設置data事件,readable會被調用兩次
rs.on('readable', function () {
    console.log('readable event');
    var chunk

    while((chunk = rs.read()) !== null) {
        console.log(chunk)
    }
})

使用可讀流發送數據

  • 可讀流在接收者麼哦呦讀取數據以前會緩存全部壓入的數據
var stream = require('stream')
var rs = new stream.Readable

rs.push('Stream')  //發送數據
rs.push('Readable')
rs.push('Push()')
rs.push('Pipe()')
rs.push('\n')
rs.push(null)  //通知發送數據完畢
rs.pipe(process.stdout)  //pipe方法導出數據

pipe方法

  • 使用pipe時回自動調用data/end事件
//複製文件
var readable = fs.createReadStream('a.js');
var writeable = fs.createWriteStream('c.js');
readable.pipe(writeable)

unpipe方法

  • 會解除以前調用pipe所設定的流;
var readable = fs.createReadStream('a.js');
var writeable = fs.createWriteStream('c.js');
readable.pipe(writeable)

//指定了目標c.js文件會變空白
readable.unpipe(writeable);
writeable.end()


//指定了目標但沒有創建導流, 不會影響
setTimeout(function (){
    readable.unpipe(writeable);
    writeable.end()
}, 100)

可寫流

  • ws.write方法向底層系統寫入數據,並在數據被處理完畢後調用回調函數;若是數據滯留在內部則返回false
var fs = require('fs')

var ws = fs.createWriteStream('1.txt');
ws.write('stream-');
ws.write('writable-');
ws.write('file-');
ws.end('end\n')

二者共同使用

var fs = require('fs')

var rs = fs.createReadStream('a.js');
var ws = fs.createWriteStream('1.txt');

rs.setEncoding('utf8')

rs.on('data', function (chunk) {
    if(ws.write(chunk) === false) rs.pause()
})

ws.on('drain', function () {
    rs.resume()
})

//ws.end被調用且全部數據已經被寫入底層系統
ws.on('finish', function() {
    console.log('ws finish');
})

rs.on('end', function () {
    ws.end()
})

http

http服務器

var http = require('http')
var url = require('url')

http.createServer(function (req, res) {
        var pathname = url.parse(req.url).pathname
        if(pathname === '/') {
            res.writeHead(200, {'Content-Type': 'text/html'})
            res.write('<h3>Nodejs-Http</h3>')
        res.end('<p>Create Basic HTTP Server!</p>')
        } else {
            res.writeHead(301, {'Location':'/'})
            res.end()
        }
}).listen(3000)
  • setHeader/getHeader: setHeader方法用於讀取一個在隊列中但沒有被髮送至客戶端的header
  • writeHeade方法只能在當前請求中使用一次,必須在write/end以前調用

http客戶端

var http = require('http')

var options = {
    hostname: '127.0.0.1',
    port: 3000,
    path: '/',
    method: 'get'
}


var req = http.request(options, function (res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8')
    var body = ''
    res.on('data', function (chunk) {
        body += chunk
    })
    res.on('end', function () {
        console.log('BODY: ' + body);
    })
})

req.on('error', function (err) {
    console.log('err: ' + err);
})

req.write('data\n')

req.end()
  • 簡化get調用: http.get(url, callback)

util

格式化字符串

util.format(format. args)

%s
%d
%j
相關文章
相關標籤/搜索