前端技術(shù)優(yōu)選 2021-09-14
以下文章來源于前端試煉 ,作者小煉
為你精選前端領(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ā)。 這些工具包的功能就是在 Node 本身的 GitHub 地址:https://github.com/isaacs/node-glob[1] 其中 如果不想使用回調(diào)的方式,可以使用同步方法 當前文件目錄如下: index.js 代碼如下: 輸出如下: 是不是發(fā)現(xiàn) GitHub 地址:https://github.com/sindresorhus/globby[3] 當前文件目錄如下: index.js 代碼如下: 輸出如下: Node 內(nèi)置了 GitHub 地址:https://github.com/jprichardson/node-fs-extra[4] 這里介紹幾個最常見的: 這幾個 NPM 包的功能主要就是會用于執(zhí)行一些系統(tǒng)命令,比如 這個包的作用就和它的名字一樣,用 GitHub 地址:https://github.com/shelljs/shelljs[5] 可以通過 除了 來看兩個 在 Node 中,可以通過 GitHub 地址:https://github.com/moxystudio/node-cross-spawn[6] 用法和 看一個比較常見的 相當于在命令行中執(zhí)行了 GitHub 地址:hhttps://github.com/isaacs/rimraf[7] 當然,也可以使用 除了在 Node 中用,在 這里主要列了兩個目前正在用的網(wǎng)絡(luò)請求的包。 相當于在 Node 上使用 Fetch。 GitHub 地址:https://github.com/node-fetch/node-fetch[8] 就舉個簡單例子,其它的看文檔就好了: GitHub 地址:https://github.com/axios/axios[9] 這里就列一堆用得上的小工具吧,按需用。 GitHub 地址:https://github.com/sindresorhus/open[10] GitHub 地址:https://github.com/http-party/http-server[11] 顧名思義, GitHub 地址:https://github.com/pillarjs/path-to-regexp[12] 比如我們的 API 的路徑有很多,其中有一部分是對外開放的 API,它的路徑是 輸出結(jié)果為: 用 GitHub 地址:https://github.com/jfromaniello/url-join[13] 假設(shè)我們需要動態(tài)地拼接參數(shù),可以這樣: 輸出結(jié)果為: GitHub 地址:https://github.com/npm/node-semver[14] 見之前的文章:實現(xiàn) CLI 常用工具包 - 終端交互相關(guān)(問卷、彩色文字、loading、進度條) 這篇文章到這里就結(jié)束了,本文整理了一些在 Node 開發(fā)時常用的 需要使用某個功能的 NPM 官網(wǎng):https://www.npmjs.com/[15] https://github.com/isaacs/node-glob: https://github.com/isaacs/node-glob 文檔: https://github.com/isaacs/node-glob#options https://github.com/sindresorhus/globby: https://github.com/sindresorhus/globby https://github.com/jprichardson/node-fs-extra: https://github.com/jprichardson/node-fs-extra https://github.com/shelljs/shelljs: https://github.com/shelljs/shelljs https://github.com/moxystudio/node-cross-spawn: https://github.com/moxystudio/node-cross-spawn hhttps://github.com/isaacs/rimraf: https://github.com/isaacs/rimraf https://github.com/node-fetch/node-fetch: https://github.com/node-fetch/node-fetch https://github.com/axios/axios: https://github.com/axios/axios https://github.com/sindresorhus/open: https://github.com/sindresorhus/open https://github.com/http-party/http-server: https://github.com/http-party/http-server https://github.com/pillarjs/path-to-regexp: https://github.com/pillarjs/path-to-regexp https://github.com/jfromaniello/url-join: https://github.com/jfromaniello/url-join https://github.com/npm/node-semver: https://github.com/npm/node-semver https://www.npmjs.com/: https://www.npmjs.com/前言
文件系統(tǒng)
fs
模塊基礎(chǔ)上提供更加方便的文件系統(tǒng)操作 API。glob
一句話介紹
glob
是一種文件匹配模式,起源于 Unix
,比如我們常見 *.js
匹配所有 js
文件就是使用了 glob
模式。使用方法
glob(pattern, [options], callback)
,glob
方法接收三個參數(shù):(error, files) => {}
options
是可選項:文檔[2],可以不傳,直接將回調(diào)函數(shù)放在第二個參數(shù)。glob.sync(pattern, options)
,用法一致,返回值即是匹配文件數(shù)組。舉例
.
├── a
│ ├── a.css
│ ├── a.js
├── .eslintrc.js
│ └── b
│ ├── b.css
│ └── b.js
├── index.js
├── package.jsonconst 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
數(shù)組。使用方法
globby(patterns, options?)
,globby
接收兩個參數(shù),返回 Promise
:舉例
.
├── a
│ ├── a.css
│ ├── a.js
├── .eslintrc.js
│ └── b
│ ├── b.css
│ └── b.js
├── index.js
├── package.jsonconst 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
一句話介紹
fs
模塊供開發(fā)者和文件系統(tǒng)交互,但是用過的同學都知道,它的能力還是挺有限的。所以,在 fs
的基礎(chǔ)上,社區(qū)提供了 fs-extra
工具包增強文件系統(tǒng)交互,并且提供了 Promise
的調(diào)用方式。舉例
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', { a: 1 }, { spaces: 2 });
// 寫 JSON 文件,如果目錄不存在會創(chuàng)建
await fse.outputJson('./c/aa.json', { a: 1 }, { spaces: 2 });
// 刪文件
await fse.remove('./a/aa.json');
})();執(zhí)行命令
npm install
、git clone
等等。shelljs
一句話介紹
js
來實現(xiàn) shell
命令。使用方法
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
一句話介紹
child_process
模塊來創(chuàng)建子進程,并且通過 child_process.spawn
方法來使用指定的命令行參數(shù)創(chuàng)建新進程,執(zhí)行完之后返回執(zhí)行結(jié)果。而 cross-spawn
包就是提供了關(guān)于 spawn
函數(shù)的跨平臺寫法,不用開發(fā)者處理跨平臺的邏輯。使用方法
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
,咳咳,是不是有點危險啊。使用方法
rimraf(f, [opts], callback)
,rimraf
方法接收三個參數(shù):rimraf.sync
同步方法。const rimraf = require('rimraf');
rimraf('./a/aa.js', error => {
if (!error) {
console.log('刪除成功');
}
});package.json
的 scripts
中也會經(jīng)常看到這個工具,比如:{
"scripts": {
"build": "rimraf build && npm run build"
}
}網(wǎng)絡(luò)請求
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
就不用介紹了,寫前端的同學都知道,用起來也很方便。使用方法
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)的。使用方法
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ù)。path-to-regexp
一句話介紹
path-to-regexp
是將指定 path
轉(zhuǎn)換成一個正則表達式的工具,一般在接口路徑匹配的時候會用到。使用方法
/openapi/*
的,可以這樣匹配:const { pathToRegexp } = require('path-to-regexp');
console.log(pathToRegexp('/openapi/:key'));/^\/openapi(?:\/([^\/#\?]+?))[\/#\?]?$/i
url-join
一句話介紹
url-join
包可以非常方便地操作一個 url,拼接任意參數(shù)。使用方法
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
規(guī)范相關(guān)的工具包,判斷版本啥的。使用方法
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)
總結(jié)
NPM
包,希望能夠幫到你。但是社區(qū)之大,功能強大的 NPM
包遠不止這些,可以自行探索。NPM
包時,可以在 NPM
官網(wǎng)或者 GitHub
上搜索:參考資料