node 12基本介绍(二)

三,基本功能模块

  1. command line options,命令行,Node.js带有各种CLI选项。这些选项提供了内置调试,执行脚本的多种方法以及其他有用的运行时选项。要在终端中以手册页形式查看此文档,请运行man node

    1
    2
    3
    4
    5
    node [options] [V8 options] [script.js | -e "script" | -] [--] [arguments]

    node inspect [script.js | -e "script" | <host>:<port>] …

    node --v8-options
  2. console,控制台模块提供了一个简单的调试控制台,类似于Web浏览器提供的JavaScript控制台机制。

  3. crtpto,加密模块提供了加密功能,其中包括用于OpenSSL哈希,HMAC,密码,解密,签名和验证功能的一组包装器。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    const crypto = require('crypto');

    const secret = 'abcdefg';
    const hash = crypto.createHmac('sha256', secret)
    .update('I love cupcakes')
    .digest('hex');
    console.log(hash);
    // Prints:
    // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
  4. Debugger, 调试器,Node.js包含一个进程外调试实用程序,可通过V8 Inspector和内置调试客户端进行访问。要使用它,请使用inspect参数启动Node.js,然后是要调试的脚本的路径。将显示提示,指示调试器已成功启动。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    $ node inspect myscript.js
    < Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba
    < For help, see: https://nodejs.org/en/docs/inspector
    < Debugger attached.
    Break on start in myscript.js:1
    > 1 (function (exports, require, module, __filename, __dirname) { global.x = 5;
    2 setTimeout(() => {
    3 console.log('world');
    debug>
  5. DNS,dns解析器,dns模块启用名称解析。例如,使用它来查找主机名的IP地址。

    1
    2
    3
    4
    5
    6
    const dns = require('dns');

    dns.lookup('example.org', (err, address, family) => {
    console.log('address: %j family: IPv%s', address, family);
    });
    // address: "93.184.216.34" family: IPv4
  6. Errors, 错误模块

    1
    2
    3
    4
    5
    6
    7
    // Throws with a ReferenceError because z is not defined.
    try {
    const m = 1;
    const n = m + z;
    } catch (err) {
    // Handle the error here.
    }
  7. Events,事件模块,Node.js核心API的大部分都基于惯用的异步事件驱动的体系结构,在该体系结构中,某些类型的对象(称为“发射器”)发出命名事件,这些事件导致调用功能对象(“侦听器”)。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    const EventEmitter = require('events');

    class MyEmitter extends EventEmitter {}

    const myEmitter = new MyEmitter();
    myEmitter.on('event', () => {
    console.log('an event occurred!');
    });
    myEmitter.emit('event');
  8. File ststem,文件系统,使用fs模块可以按照在标准POSIX函数上建模的方式与文件系统进行交互。

    1
    const fs = require('fs');
  9. Globals,全局数据。例如URL,require,process, console等

  10. 网络请求,http/http2/https等

    1
    const http = require('http');
  11. Internationalization support,国际化支持。

  12. Modules,模块系统,在Node.js模块系统中,每个文件都被视为一个单独的模块。例如,考虑一个名为foo.js的文件:

    1
    2
    const circle = require('./circle.js');
    console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);
  13. Net, net模块提供了一个异步网络API,用于创建基于流的TCP或IPC服务器(net.createServer())和客户端(net.createConnection())。

    1
    const net = require('net');
  14. OS,os模块提供与操作系统相关的实用程序方法和属性。

    1
    const os = require('os');
  15. path,路径模块,路径模块提供了用于处理文件和目录路径的实用程序。

    1
    const path = require('path');
  16. performance hooks,此模块提供W3C Web性能API的子集以及用于特定于Node.js的性能测量的其他API的实现。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    const { PerformanceObserver, performance } = require('perf_hooks');

    const obs = new PerformanceObserver((items) => {
    console.log(items.getEntries()[0].duration);
    performance.clearMarks();
    });
    obs.observe({ entryTypes: ['measure'] });
    performance.measure('Start to Now');

    performance.mark('A');
    doSomeLongRunningProcess(() => {
    performance.measure('A to Now', 'A');

    performance.mark('B');
    performance.measure('A to B', 'A', 'B');
    });
  17. process,流程对象是一个全局对象,可提供有关当前Node.js流程的信息并对其进行控制。全局而言,它始终可用于Node.js应用程序,而无需使用require()。也可以使用require()显式访问它。

    1
    const process = require('process');
  18. query string,模块提供了用于解析和格式化URL查询字符串的实用程序。

    1
    const querystring = require('querystring');
  19. readline,模块提供了一个接口,用于一次从一行的Readable流(例如process.stdin)读取数据。可以使用以下命令访问它:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    const readline = require('readline');

    const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
    });

    rl.question('What do you think of Node.js? ', (answer) => {
    // TODO: Log the answer in a database
    console.log(`Thank you for your valuable feedback: ${answer}`);

    rl.close();
    });
  20. report, 诊断报告,提供写入文件的JSON格式的诊断摘要。该报告旨在用于开发,测试和生产用途,以捕获和保存信息以用于确定问题。它包括JavaScript和本机堆栈跟踪,堆统计信息,平台信息,资源使用情况等。启用报告选项后,除了通过API调用以编程方式触发之外,还可以针对未处理的异常,致命错误和用户信号触发诊断报告。

    1
    process.report.writeReport('./foo.json');
  21. stream,流是用于在Node.js中处理流数据的抽象接口。流模块提供用于实现流接口的API。

    1
    const stream = require('stream');
  22. string decoder,模块提供了一个API,用于以保留编码的多字节UTF-8和UTF-16字符的方式将Buffer对象解码为字符串。可以使用以下命令访问它:

    1
    2
    3
    4
    5
    6
    7
    8
    const { StringDecoder } = require('string_decoder');
    const decoder = new StringDecoder('utf8');

    const cent = Buffer.from([0xC2, 0xA2]);
    console.log(decoder.write(cent));

    const euro = Buffer.from([0xE2, 0x82, 0xAC]);
    console.log(decoder.write(euro));
  23. Timers,计时器模块公开了全局API,用于计划在将来的某个时间段调用的功能。由于计时器函数是全局函数,因此无需调用require(’timers’)即可使用API。Node.js中的计时器函数实现了与Web浏览器提供的计时器API类似的API,但是使用了围绕Node.js事件循环构建的不同内部实现。

  24. TLS,SSL,tls模块提供了在OpenSSL之上构建的传输层安全性(TLS)和安全套接字层(SSL)协议的实现。可以使用以下命令访问该模块:

    1
    const tls = require('tls');
  25. udp,dgram模块提供UDP数据报套接字的实现。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    const dgram = require('dgram');
    const server = dgram.createSocket('udp4');

    server.on('error', (err) => {
    console.log(`server error:\n${err.stack}`);
    server.close();
    });

    server.on('message', (msg, rinfo) => {
    console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
    });

    server.on('listening', () => {
    const address = server.address();
    console.log(`server listening ${address.address}:${address.port}`);
    });

    server.bind(41234);
    // Prints: server listening 0.0.0.0:41234
  26. url,模块提供用于URL解析和解析的实用程序。可以使用以下命令访问它。

    1
    const url = require('url');
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    ┌────────────────────────────────────────────────────────────────────────────────────────────────┐
    │ href │
    ├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
    │ protocol │ │ auth │ host │ path │ hash │
    │ │ │ ├─────────────────┬──────┼──────────┬────────────────┤ │
    │ │ │ │ hostname │ port │ pathname │ search │ │
    │ │ │ │ │ │ ├─┬──────────────┤ │
    │ │ │ │ │ │ │ │ query │ │
    " https: // user : pass @ sub.example.com : 8080 /p/a/t/h ? query=string #hash "
    │ │ │ │ │ hostname │ port │ │ │ │
    │ │ │ │ ├─────────────────┴──────┤ │ │ │
    │ protocol │ │ username │ password │ host │ │ │ │
    ├──────────┴──┼──────────┴──────────┼────────────────────────┤ │ │ │
    │ origin │ │ origin │ pathname │ search │ hash │
    ├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
    │ href │
    └────────────────────────────────────────────────────────────────────────────────────────────────┘
    (All spaces in the "" line should be ignored. They are purely for formatting.)
  27. util,模块支持Node.js内部API的需求。许多实用程序对应用程序和模块开发人员也很有用。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    const util = require('util');
    const fs = require('fs');

    const stat = util.promisify(fs.stat);

    async function callStat() {
    const stats = await stat('.');
    console.log(`This directory is owned by ${stats.uid}`);
    }
  28. v8,模块公开了特定于Node.js二进制文件中内置的V8版本的API。可以使用以下命令访问它:

  29. VM,模块可在V8虚拟机上下文中编译和运行代码。 vm模块不是安全机制。不要使用它来运行不受信任的代码。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    const vm = require('vm');

    const x = 1;

    const context = { x: 2 };
    vm.createContext(context); // Contextify the object.

    const code = 'x += 40; var y = 17;';
    // `x` and `y` are global variables in the context.
    // Initially, x has the value 2 because that is the value of context.x.
    vm.runInContext(code, context);

    console.log(context.x); // 42
    console.log(context.y); // 17

    console.log(x); // 1; y is not defined.
  30. webAssembly,WASI API提供了WebAssembly系统接口规范的实现。 WASI通过类似于POSIX的功能的集合,使沙盒WebAssembly应用程序可以访问底层操作系统。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    'use strict';
    const fs = require('fs');
    const { WASI } = require('wasi');
    const wasi = new WASI({
    args: process.argv,
    env: process.env,
    preopens: {
    '/sandbox': '/some/real/path/that/wasm/can/access'
    }
    });
    const importObject = { wasi_snapshot_preview1: wasi.wasiImport };

    (async () => {
    const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));
    const instance = await WebAssembly.instantiate(wasm, importObject);

    wasi.start(instance);
    })();
  31. worker_threads,模块允许使用并行执行JavaScript的线程。worker_threads(线程)对于执行CPU密集型JavaScript操作非常有用。他们在I / O密集型工作中无济于事。 Node.js的内置异步I / O操作比Workers效率更高。与child_process或cluster不同,worker_threads可以共享内存。它们通过传输ArrayBuffer实例或共享SharedArrayBuffer实例来实现。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    const {
    Worker, isMainThread, parentPort, workerData
    } = require('worker_threads');

    if (isMainThread) {
    module.exports = function parseJSAsync(script) {
    return new Promise((resolve, reject) => {
    const worker = new Worker(__filename, {
    workerData: script
    });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', (code) => {
    if (code !== 0)
    reject(new Error(`Worker stopped with exit code ${code}`));
    });
    });
    };
    } else {
    const { parse } = require('some-js-parsing-library');
    const script = workerData;
    parentPort.postMessage(parse(script));
    }
  32. zlib,模块提供了使用Gzip,Deflate / Inflate和Brotli实现的压缩功能。压缩或解压缩流(例如文件)可以通过将源流通过zlib Transform流传递到目标流中来实现:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    const { createGzip } = require('zlib');
    const { pipeline } = require('stream');
    const {
    createReadStream,
    createWriteStream
    } = require('fs');

    const gzip = createGzip();
    const source = createReadStream('input.txt');
    const destination = createWriteStream('input.txt.gz');

    pipeline(source, gzip, destination, (err) => {
    if (err) {
    console.error('An error occurred:', err);
    process.exitCode = 1;
    }
    });

    // Or, Promisified

    const { promisify } = require('util');
    const pipe = promisify(pipeline);

    async function do_gzip(input, output) {
    const gzip = createGzip();
    const source = createReadStream(input);
    const destination = createWriteStream(output);
    await pipe(source, gzip, destination);
    }

    do_gzip('input.txt', 'input.txt.gz')
    .catch((err) => {
    console.error('An error occurred:', err);
    process.exitCode = 1;
    });

基本上总结完毕,梳理这个内容,让自己对node有一个直观的了解,知道它有哪些功能,对自己使用node很有帮助。