看了就會的 Node.js 常用三方工具包


文件系統

這些工具包的功能就是在 Node 本身的 fs 模塊基礎上提供更加方便的文件系統操作 API。

glob

一句話介紹

glob 是一種文件匹配模式,起源於 Unix,比如我們常見 *.js 匹配所有 js 文件就是使用了 glob 模式。

GitHub 地址:https://github.com/isaacs/node-glob

使用方法

glob(pattern, [options], callback)glob 方法接收三個參數:

  • pattern: 匹配規則字符串
  • options: 配置項(可選)
  • callback: 回調函數 (error, files) => {}
    • error: 錯誤信息,如果不存在則為成功
    • matches: 匹配文件數組

其中 options 是可選項,可以不傳,直接將回調函數放在第二個參數。

如果不想使用回調的方式,可以使用同步方法 glob.sync(pattern, options),用法一致,返回值即是匹配文件數組。

舉例

當前文件目錄如下:

.
├── a
│   ├── a.css
│   ├── a.js
    ├── .eslintrc.js
│   └── b
│       ├── b.css
│       └── b.js
├── index.js
├── package.json

index.js 代碼如下:

const glob = require("glob")

glob("a/**/*.js", (error, matches) => {
  if (!error) {
    console.log(matches);
  }
});

try {
  const files = glob.sync("a/**/*.js");
  console.log(files);
} catch (e) {}
 

輸出如下:

[ 'a/a.js', 'a/b/b.js' ]
 

是不是發現 .eslintrc.js 文件並沒有被匹配到。默認情況下,glob 不會匹配以 . 開頭的文件,需要我們在配置項中打開:

const glob = require("glob")

glob("a/**/*.js", { dot: true }, (error, matches) => {
  if (!error) {
    console.log(matches);
  }
});
// [ 'a/.eslintrc.js', 'a/a.js', 'a/b/b.js' ]
 

globby

一句話介紹

globby 是增強型的 glob,提供了 Promise 的封裝。最終要的是它支持多模式匹配,相比於 glob 只能傳入一個 pattern 字符串,globby 支持傳入一個 pattern 數組。

GitHub 地址:https://github.com/sindresorhus/globby

使用方法

globby(patterns, options?)globby 接收兩個參數,返回 Promise

  • patterns: 匹配規則數組
  • options: 配置項

舉例

當前文件目錄如下:

.
├── a
│   ├── a.css
│   ├── a.js
    ├── .eslintrc.js
│   └── b
│       ├── b.css
│       └── b.js
├── index.js
├── package.json

index.js 代碼如下:

const globby = require('globby');

(async () => {
  const files = await globby(['a/**/*.js', 'a/**/*.css'], { dot: true });
  console.log(files);
})();
 

輸出如下:

[ 'a/.eslintrc.js', 'a/a.js', 'a/b/b.js', 'a/a.css', 'a/b/b.css' ]

fs-extra

一句話介紹

Node 內置了 fs 模塊供開發者和文件系統交互,但是用過的同學都知道,它的能力還是挺有限的。所以,在 fs 的基礎上,社區提供了 fs-extra 工具包增強文件系統交互,並且提供了 Promise 的調用方式。

GitHub 地址:https://github.com/jprichardson/node-fs-extra

舉例

這里介紹幾個最常見的:

const fse = require('fs-extra');

(async () => {
  // 確認目錄是否存在,如果不存在會創建目錄
  await fse.ensureDir('./a');

  // 復制文件
  await fse.copy('./a/a.js', './a/aa.js');

  // 讀 JSON 文件
  const aJSON = await fse.readJSON('./a/a.json');
  console.log(typeof aJSON, aJSON);

  // 寫 JSON 文件
  await fse.writeJSON('./a/aa.json', { a: 1 }, { spaces: 2 });

  // 寫 JSON 文件,如果目錄不存在會創建
  await fse.outputJson('./c/aa.json', { a: 1 }, { spaces: 2 });

  // 刪文件
  await fse.remove('./a/aa.json');
})();
 

執行命令

這幾個 NPM 包的功能主要就是會用於執行一些系統命令,比如 npm installgit clone 等等。

shelljs

一句話介紹

這個包的作用就和它的名字一樣,用 js 來實現 shell 命令。

GitHub 地址:https://github.com/shelljs/shelljs

使用方法

可以通過 shelljs 提供的 exec 命令同步地執行任意的 shell 命令,返回值中的 code 標識是否成功執行,比如:

const shell = require('shelljs');

if (shell.exec('git init .').code === 0) {
  console.log('Git 初始化成功');
}
 

除了 exec 之外,shelljs 也提供了一些常用 shell 命令的包裝,比如 whichecho 等,比如:

const shell = require('shelljs');

shell.echo('Hello Shelljs');
 

舉例

來看兩個 shelljs 的常見用法。

const shell = require('shelljs');

// 判斷是否有相關開發環境
function hasGitNpm() {
  if (!shell.which('git')) {
    console.log('Sorry, this script requires git');
    shell.exit(1);
  }

  if (!shell.which('npm')) {
    console.log('Sorry, this script requires npm');
    shell.exit(1);
  }
}

hasGitNpm();

// 安裝 npm 包
function installPkg(pkg, type) {
  const npm = shell.which('npm');
  if (!npm) {
    console.log('請先安裝 npm');
    return;
  }
  const { code } = shell.exec(
    `${npm.stdout} install ${pkg} ${type || '--save'}`
  );
  if (code) {
    console.log(`安裝 ${pkg} 失敗,請手動安裝`);
  }
}

installPkg('lodash');
 

cross-spawn

一句話介紹

在 Node 中,可以通過 child_process 模塊來創建子進程,並且通過 child_process.spawn 方法來使用指定的命令行參數創建新進程,執行完之后返回執行結果。而 cross-spawn 包就是提供了關於 spawn 函數的跨平台寫法,不用開發者處理跨平台的邏輯。

GitHub 地址:https://github.com/moxystudio/node-cross-spawn

使用方法

用法和 child_process.spawn(command[, args][, options]) 保持一致:

const spawn = require('cross-spawn');

const child = spawn('npm', ['install'], { stdio: 'inherit' });
 

舉例

看一個比較常見的 cross-spawn 用法:

const spawn = require('cross-spawn');

// 安裝全部依賴
spawn.sync('npm', ['install'], { stdio: 'inherit' });

// 安裝指定依賴
spawn.sync('npm', ['install', 'lodash', '--save'], { stdio: 'inherit' });
 

rimraf

一句話介紹

相當於在命令行中執行了 rm -rf,咳咳,是不是有點危險啊。

GitHub 地址:hhttps://github.com/isaacs/rimraf

使用方法

rimraf(f, [opts], callback)rimraf 方法接收三個參數:

  • f: glob 匹配規則
  • opts: 配置項,可選
  • callback: 回調函數

當然,也可以使用 rimraf.sync 同步方法。

const rimraf = require('rimraf');

rimraf('./a/aa.js', error => {
  if (!error) {
    console.log('刪除成功');
  }
});
 

除了在 Node 中用,在 package.json 的 scripts 中也會經常看到這個工具,比如:

{
  "scripts": {
    "build": "rimraf build && npm run build"
  }
}
 

網絡請求

這里主要列了兩個目前正在用的網絡請求的包。

node-fetch

一句話介紹

相當於在 Node 上使用 Fetch。

GitHub 地址:https://github.com/node-fetch/node-fetch

使用方法

就舉個簡單例子,其它的看文檔就好了:

const fetch = require('node-fetch');

const response = await fetch('https://api.github.com/users/github');
const data = await response.json();

console.log(data);
 

axios

一句話介紹

axios 就不用介紹了,寫前端的同學都知道,用起來也很方便。

GitHub 地址:https://github.com/axios/axios

使用方法

const axios = require('axios');

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
 

小工具

這里就列一堆用得上的小工具吧,按需用。

open

一句話介紹

open 包可以讓你在代碼中打開網頁、圖片等等。比如你經常 npm start 啟動項目的時候,是不是會自動喚起瀏覽器打開一個 localhost 的頁面,就是通過 open 包實現的。

GitHub 地址:https://github.com/sindresorhus/open

使用方法

const open = require('open');

await open('http://localhost:8080');
 

http-server

一句話介紹

http-server 包一般安裝在全局使用,可以在本地任意目錄 0 配置啟動一個 HTTP 服務,一般在本地開發和測試的時候會經常用到。比如,使用 npm build 打包構建出構建產物之后,可以本地執行 http-server build 啟動一個服務。

GitHub 地址:https://github.com/http-party/http-server

path-to-regexp

一句話介紹

顧名思義,path-to-regexp 是將指定 path 轉換成一個正則表達式的工具,一般在接口路徑匹配的時候會用到。

GitHub 地址:https://github.com/pillarjs/path-to-regexp

使用方法

比如我們的 API 的路徑有很多,其中有一部分是對外開放的 API,它的路徑是 /openapi/* 的,可以這樣匹配:

const { pathToRegexp } = require('path-to-regexp');

console.log(pathToRegexp('/openapi/:key'));
 

輸出結果為:

/^\/openapi(?:\/([^\/#\?]+?))[\/#\?]?$/i
 

url-join

一句話介紹

用 url-join 包可以非常方便地操作一個 url,拼接任意參數。

GitHub 地址:https://github.com/jfromaniello/url-join

使用方法

假設我們需要動態地拼接參數,可以這樣:

const urlJoin = require('url-join');

console.log(urlJoin('http://www.google.com', 'a', '/b/cd', '?foo=123'));
 

輸出結果為:

http://www.google.com/a/b/cd?foo=123

semver

一句話介紹

NPM 的 semver 規范相關的工具包,判斷版本啥的。

GitHub 地址:https://github.com/npm/node-semver

使用方法

const semver = require('semver')

// 判斷是否符合規范
semver.valid('1.2.3') // '1.2.3'
semver.valid('a.b.c') // null
// 判斷 a 版本是否比 b 版本高
semver.gt('1.2.3', '9.8.7') // false
// 判斷 a 版本是否比 b 版本低
semver.lt('1.2.3', '9.8.7') // true
// 判斷符合某個版本范圍的最低版本
semver.minVersion('>=1.0.0') // '1.0.0'
 

CLI 相關

見之前的文章:實現 CLI 常用工具包 - 終端交互相關(問卷、彩色文字、loading、進度條)

總結

這篇文章到這里就結束了,本文整理了一些在 Node 開發時常用的 NPM 包,希望能夠幫到你。但是社區之大,功能強大的 NPM 包遠不止這些,可以自行探索。

需要使用某個功能的 NPM 包時,可以在 NPM 官網或者 GitHub 上搜索:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM