精品伊人久久大香线蕉,开心久久婷婷综合中文字幕,杏田冲梨,人妻无码aⅴ不卡中文字幕

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

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

前端技術(shù)優(yōu)選 2021-09-14

以下文章來源于前端試煉 ,作者小煉

前端試煉

每天一篇精心挑選的高質(zhì)量文章,專注深度和最佳實踐,希望打造一個高質(zhì)量的公眾號。

點擊下方“前端技術(shù)優(yōu)選”,選擇“設(shè)為星標
第一時間關(guān)注技術(shù)干貨!

前端技術(shù)優(yōu)選

為你精選前端領(lǐng)域優(yōu)質(zhì)技術(shù)博文,歡迎關(guān)注。

69篇原創(chuàng)內(nèi)容

公眾號

前言

之前一篇文章介紹了 Node.js 的三個模塊的基礎(chǔ) API,面對文檔時不那么抓瞎,基礎(chǔ) API 用習慣了也差不多找到感覺,之后想用啥就可以自己照著文檔找就好了。

除了 Node 提供的基礎(chǔ)模塊之外,我們在開發(fā)中必不可少地會用到第三方模塊,也就是我們最常見的社區(qū) NPM 包。這篇文章主要就是介紹一些在開發(fā) Node 的時候,常用的一些基礎(chǔ)工具包。

兩篇文章配合使用,應(yīng)該可以幫助你上手 Node 開發(fā)。

文件系統(tǒng)

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

glob

一句話介紹

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

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

使用方法

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

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

其中 options 是可選項:文檔[2],可以不傳,直接將回調(diào)函數(shù)放在第二個參數(shù)。

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

舉例

當前文件目錄如下:

.
├── 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' ]

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

const glob = require("glob")

glob("a/**/*.js", { dottrue }, (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 數(shù)組。

GitHub 地址:https://github.com/sindresorhus/globby[3]

使用方法

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

  • patterns: 匹配規(guī)則數(shù)組
  • 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'], { dottrue });
  console.log(files);
})();

輸出如下:

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

fs-extra

一句話介紹

Node 內(nèi)置了 fs 模塊供開發(fā)者和文件系統(tǒng)交互,但是用過的同學都知道,它的能力還是挺有限的。所以,在 fs 的基礎(chǔ)上,社區(qū)提供了 fs-extra 工具包增強文件系統(tǒng)交互,并且提供了 Promise 的調(diào)用方式。

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

舉例

這里介紹幾個最常見的:

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

(async () => {
  // 確認目錄是否存在,如果不存在會創(chuàng)建目錄
  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', { a1 }, { spaces2 });

  // 寫 JSON 文件,如果目錄不存在會創(chuàng)建
  await fse.outputJson('./c/aa.json', { a1 }, { spaces2 });

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

執(zhí)行命令

這幾個 NPM 包的功能主要就是會用于執(zhí)行一些系統(tǒng)命令,比如 npm install、git clone 等等。

shelljs

一句話介紹

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

GitHub 地址:https://github.com/shelljs/shelljs[5]

使用方法

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

const shell = require('shelljs');

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

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

const shell = require('shelljs');

shell.echo('Hello Shelljs');

舉例

來看兩個 shelljs 的常見用法。

const shell = require('shelljs');

// 判斷是否有相關(guān)開發(fā)環(huán)境
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 模塊來創(chuàng)建子進程,并且通過 child_process.spawn 方法來使用指定的命令行參數(shù)創(chuàng)建新進程,執(zhí)行完之后返回執(zhí)行結(jié)果。而 cross-spawn 包就是提供了關(guān)于 spawn 函數(shù)的跨平臺寫法,不用開發(fā)者處理跨平臺的邏輯。

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

使用方法

用法和 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

一句話介紹

相當于在命令行中執(zhí)行了 rm -rf,咳咳,是不是有點危險啊。

GitHub 地址:hhttps://github.com/isaacs/rimraf[7]

使用方法

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

  • f: glob 匹配規(guī)則
  • opts: 配置項,可選
  • callback: 回調(diào)函數(shù)

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

const rimraf = require('rimraf');

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

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

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

網(wǎng)絡(luò)請求

這里主要列了兩個目前正在用的網(wǎng)絡(luò)請求的包。

node-fetch

一句話介紹

相當于在 Node 上使用 Fetch。

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

使用方法

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

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[9]

使用方法

const axios = require('axios');

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

小工具

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

open

一句話介紹

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

GitHub 地址:https://github.com/sindresorhus/open[10]

使用方法

const open = require('open');

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

http-server

一句話介紹

http-server 包一般安裝在全局使用,可以在本地任意目錄 0 配置啟動一個 HTTP 服務(wù),一般在本地開發(fā)和測試的時候會經(jīng)常用到。比如,使用 npm build 打包構(gòu)建出構(gòu)建產(chǎn)物之后,可以本地執(zhí)行 http-server build 啟動一個服務(wù)。

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

path-to-regexp

一句話介紹

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

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

使用方法

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

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

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

輸出結(jié)果為:

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

url-join

一句話介紹

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

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

使用方法

假設(shè)我們需要動態(tài)地拼接參數(shù),可以這樣:

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

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

輸出結(jié)果為:

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

semver

一句話介紹

NPM 的 semver 規(guī)范相關(guān)的工具包,判斷版本啥的。

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

使用方法

const semver = require('semver')

// 判斷是否符合規(guī)范
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 相關(guān)

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

總結(jié)

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

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

NPM 官網(wǎng)https://www.npmjs.com/[15]

參考資料

[1]

https://github.com/isaacs/node-glob: https://github.com/isaacs/node-glob

[2]

文檔: https://github.com/isaacs/node-glob#options

[3]

https://github.com/sindresorhus/globby: https://github.com/sindresorhus/globby

[4]

https://github.com/jprichardson/node-fs-extra: https://github.com/jprichardson/node-fs-extra

[5]

https://github.com/shelljs/shelljs: https://github.com/shelljs/shelljs

[6]

https://github.com/moxystudio/node-cross-spawn: https://github.com/moxystudio/node-cross-spawn

[7]

hhttps://github.com/isaacs/rimraf: https://github.com/isaacs/rimraf

[8]

https://github.com/node-fetch/node-fetch: https://github.com/node-fetch/node-fetch

[9]

https://github.com/axios/axios: https://github.com/axios/axios

[10]

https://github.com/sindresorhus/open: https://github.com/sindresorhus/open

[11]

https://github.com/http-party/http-server: https://github.com/http-party/http-server

[12]

https://github.com/pillarjs/path-to-regexp: https://github.com/pillarjs/path-to-regexp

[13]

https://github.com/jfromaniello/url-join: https://github.com/jfromaniello/url-join

[14]

https://github.com/npm/node-semver: https://github.com/npm/node-semver

[15]

https://www.npmjs.com/: https://www.npmjs.com/

本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
如何用 Babel 為代碼自動引入依賴
安裝ionic 是到SASS軟件包無法下載的問題 Cannot download https://github.com/sass/node-sass/releases/download/v
關(guān)于 Appium 各種版本的安裝,都在這里
Deno 運行時入門教程:Node.js 的替代品
軟件推薦(typora) -- 結(jié)合markdown、gitbook文檔生產(chǎn)力輸出
還在手擼 Nginx 配置?試試這款可視化配置工具吧,真心強大!
更多類似文章 >>
生活服務(wù)
分享 收藏 導長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服

主站蜘蛛池模板: 综艺| 勐海县| 永安市| 清镇市| 开鲁县| 朝阳县| 鄯善县| 嵩明县| 海城市| 临颍县| 个旧市| 凤山市| 北川| 乐都县| 涿州市| 连南| 司法| 长顺县| 桂平市| 昭觉县| 杂多县| 惠东县| 彭泽县| 清苑县| 峨山| 汉源县| 屏南县| 嘉义市| 三穗县| 三门县| 梓潼县| 白山市| 纳雍县| 扶余县| 宜州市| 礼泉县| 固镇县| 盐亭县| 紫阳县| 壶关县| 农安县|