Node.js 代码段

一些常用或有用的代码段,积少成多。

http

  • server
    1
    2
    3
    4
    5
    6
    7
    const http = require('http');

    http.createServer((request, response) => {
    response.writeHead(200, { 'Content-Type': 'text/plain;charset=utf-8'});

    response.end('你好,跳跳');
    }).listen(8080);
  • request
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    const http = require('http');
    const option = {
    hostname: '127.0.0.1',
    port: 8080,
    path: '/',
    method: 'GET'
    };

    const req = http.request(option, (res) => {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
    console.log(chunk);
    });
    });

    req.end();

Stream

  • ReadStream/WriteStream
1
2
3
4
5
6
7
8
9
10
11
12
13
const fs = require('fs');

function copyFile(source, dist) {
const readStream = fs.createReadStream(source);
const writeStream = fs.createWriteStream(dist);

readStream.on('data', (chunk) => {
writeStream.write(chunk);
});

// 或者
fs.createReadStream(source).pipe(fs.createWriteStream(dist));
}