Skip to content

引入

ts
import {
  getChildProcess,
  getCrypto,
  getFs,
  getHttp,
  getNet,
  getOs,
  getPath,
  getRequest,
  getUtil
} from 't-comm';

// 不支持 tree-shaking 的项目
import {
  getChildProcess,
  getCrypto,
  getFs,
  getHttp,
  getNet,
  getOs,
  getPath,
  getRequest,
  getUtil
} from 't-comm/lib/nodejs/index';

// 只支持 ESM 的项目
import {
  getChildProcess,
  getCrypto,
  getFs,
  getHttp,
  getNet,
  getOs,
  getPath,
  getRequest,
  getUtil
} from 't-comm/es/nodejs/index';

getChildProcess()

描述:获取 Node.js child_process 模块(仅支持 Node.js 环境)

Throws:

  • Error 当在非 Node.js 环境中调用时抛出错误

参数

返回: child_process 模块

示例

ts
const cp = getChildProcess();
cp.exec('ls -la', (error, stdout, stderr) => {
  console.log(stdout);
});

getCrypto()

描述:获取 Node.js 的 crypto 模块 这样可以避免在浏览器环境中直接导入 crypto 模块导致的错误

参数

返回: crypto 模块

示例

ts
const crypto = getCrypto();
const hash = crypto.createHash('md5').update('hello').digest('hex');

getFs()

描述:仅在 Node.js 环境中可用

参数

返回: fs 模块

示例

ts
import { getFs } from 't-comm';
const fs = getFs();
fs.readFileSync('path/to/file', 'utf-8');

getHttp()

描述:仅在 Node.js 环境中可用

参数

返回: http 模块

示例

ts
import { getHttp } from 't-comm';
const http = getHttp();
http.request(options, callback);

getNet()

描述:获取 Node.js 的 net 模块 这样可以避免在浏览器环境中直接导入 net 模块导致的错误

参数

返回: net 模块

示例

ts
const net = getNet();
const server = net.createServer((socket) => {
  socket.write('hello\n');
  socket.end();
});
server.listen(3000);

getOs()

描述:仅在 Node.js 环境中可用

参数

返回: os 模块

示例

ts
import { getOs } from 't-comm';
const os = getOs();
const tmpDir = os.tmpdir();

getPath()

描述:获取 Node.js path 模块 动态导入 path 模块,避免在浏览器环境中引起错误

参数

返回: Node.js path 模块

示例

ts
const path = getPath();
const fullPath = path.resolve(__dirname, './file.txt');
const basename = path.basename('/path/to/file.txt'); // 'file.txt'

getRequest()

描述:获取 request 库 request 是一个第三方 HTTP 客户端库 注意:request 库已经被废弃,建议使用 axios 或 node-fetch 替代

参数

返回: request 库

示例

ts
const request = getRequest();
request('https://example.com', (err, response, body) => {
  if (err) return console.error(err);
  console.log(body);
});

getUtil()

描述:获取 Node.js 的 util 模块 这样可以避免在浏览器环境中直接导入 util 模块导致的错误

参数

返回: util 模块

示例

ts
const util = getUtil();
console.log(util.format('%s + %s = %s', 1, 2, 3)); // '1 + 2 = 3'

const promisify = util.promisify(fs.readFile);
const data = await promisify('./a.txt', 'utf-8');