卜娃娃|nodejs 的融会贯通,你学会了吗?( 三 )

DNS 请求使用 dns 模块创建 DNS 请求 。

  • A:`dns.resolve` , A 记录存储 IP 地址
  • TXT:`dns.resulveTxt` , 文本值可以用于在 - DNS 上构建其他服务
  • SRV:`dns.resolveSrv` , 服务记录定义服务的定位数据 , 通常包含主机名和端口号
  • NS:`dns.resolveNs` , 指定域名服务器
  • CNAME:`dns.resolveCname` , 相关的域名记录 , 设置为域名而不是 IP 地址 const dns = require('dns'); dns.resolve('www.chenng.cn', function (err, addresses) { if (err) { console.error(err); } console.log('Addresses:', addresses); 复制代码 });
crypto 库加密解密const crypto = require('crypto')function aesEncrypt(data, key = 'key') {const cipher = crypto.createCipher('aes192', key)let crypted = cipher.update(data, 'utf8', 'hex')crypted += cipher.final('hex')return crypted}function aesDecrypt(encrypted, key = 'key') {const decipher = crypto.createDecipher('aes192', key)let decrypted = decipher.update(encrypted, 'hex', 'utf8')decrypted += decipher.final('utf8')return decrypted}复制代码发起 HTTP 请求的方法
  • HTTP 标准库
  • 无需安装外部依赖
  • 需要以块为单位接受数据 , 自己监听 end 事件
  • HTTP 和 HTTPS 是两个模块 , 需要区分使用
  • Request 库
  • 使用方便
  • 有 promise 版本 request-promise
  • Axios
  • 既可以用在浏览器又可以用在 NodeJS
  • 可以使用 axios.all 并发多个请求
  • SuperAgent
  • 可以链式使用
  • node-fetch
  • 浏览器的 fetch 移植过来的
子进程执行外部应用基本概念
  • 4个异步方法:exec、execFile、fork、spawn
  • spawn:处理一些会有很多子进程 I/O 时、进程会有大量输出时使用
  • execFile:只需执行一个外部程序的时候使用 , 执行速度快 , 处理用户输入相对安全
  • exec:想直接访问线程的 shell 命令时使用 , 一定要注意用户输入
  • fork:想将一个 Node 进程作为一个独立的进程来运行的时候使用 , 是的计算处理和文件描述器脱离 Node 主进程
  • Node
  • 非 Node
  • 3个同步方法:execSync、execFileSync、spawnSync
  • 通过 API 创建出来的子进程和父进程没有任何必然联系
execFile会把输出结果缓存好 , 通过回调返回最后结果或者异常信息
const cp = require('child_process');cp.execFile('echo', ['hello', 'world'], (err, stdout, stderr) => {if (err) {console.error(err);}console.log('stdout: ', stdout);console.log('stderr: ', stderr);});复制代码pawn
  • 通过流可以使用有大量数据输出的外部应用 , 节约内存
  • 使用流提高数据响应效率
  • spawn 方法返回一个 I/O 的流接口
单一任务
const cp = require('child_process');const child = cp.spawn('echo', ['hello', 'world']);child.on('error', console.error);child.stdout.pipe(process.stdout);child.stderr.pipe(process.stderr);复制代码多任务串联
const cp = require('child_process');const path = require('path');const cat = cp.spawn('cat', [path.resolve(__dirname, 'messy.txt')]);const sort = cp.spawn('sort');const uniq = cp.spawn('uniq');cat.stdout.pipe(sort.stdin);sort.stdout.pipe(uniq.stdin);uniq.stdout.pipe(process.stdout);复制代码exec