在前端實際項目開發(fā)中,會有這樣一種場景。每次引入新的圖片,并不知道這個資源是否被引用過,所以會點開存放圖片的資源一個個去看。實際問題是:
-
1.圖片并不是放到一個目錄下的,可能存在任何的地方,不好查找
-
2.費時間,費力
-
3.可能會重復(fù)引入圖片資源
如果有個能力,將項目圖片資源羅列到一起查看,并方便看到引入路徑的話,就會大大節(jié)約開發(fā)的體力活。
如果要做這樣的能力,應(yīng)該考慮什么呢?
需求分析
-
可以集成到任何前端項目中,那就要求是個
npm包
-
讀取文件,分析哪些是圖片,將圖片資源通過
img標(biāo)簽
寫入到html文件中 -
創(chuàng)建一個服務(wù)器,將html渲染出來
這就需要借助Node來實現(xiàn),需要用到的 fs
path
http
模塊?!鞠嚓P(guān)教程推薦:nodejs視頻教程、編程教學(xué)】
實現(xiàn)
1 實現(xiàn)可發(fā)布npm包
-
創(chuàng)建一個項目
npm init
包名字是
test-read-img
-
在package.json 中加入如下代碼
"bin": { "readimg": "./index.js" },
-
在入口文件index.js 中加入測試代碼
含義是這個文件是可執(zhí)行的node文件
#!/usr/bin/env node console.log('111')
登錄后復(fù)制 -
將當(dāng)前模塊鏈接到全局node_modules模塊內(nèi),方便調(diào)試
執(zhí)行
npm link
執(zhí)行
readimg
就看到輸出111 了
到此就實現(xiàn)了通過命令使用npm包的使用了,當(dāng)項目安裝了這個包,并配置執(zhí)行命令,就可以在別的項目執(zhí)行設(shè)計的npm包了,后面就實現(xiàn)這個
"scripts": { "test": "readimg" },
登錄后復(fù)制
2 集成到別的項目
- 創(chuàng)建一個測試項目 ,執(zhí)行
npm init
- 將測試包集成到當(dāng)前項目, 執(zhí)行
npm link test-read-img
- 配置執(zhí)行命令
"scripts": { "test": "readimg" },
執(zhí)行npm run test
就能看到當(dāng)前項目執(zhí)行了讀取文件的包的代碼了。 現(xiàn)在只輸出了 111距離讀取文件還很遠,下面來實現(xiàn)讀取文件
3 讀取文件
- 在
test-read-img
項目中,聲明一個執(zhí)行函數(shù),并執(zhí)行.
#!/usr/bin/env node const init = async () => { const readFiles = await getFileFun(); const html = await handleHtml(readFiles); createServer(html); } init();
這里解釋一下 ,各函數(shù)作用
getFileFun
: 讀取項目文件,并將讀取的圖片文件路徑返回,這里不需要圖片資源,后面解釋為什么。
handleHtml
: 讀取模版html文件, 將圖片資源通過 img
承載 生成新的html文件。
createServer
: 將生成的html ,放到服務(wù)器下去渲染出來。
主流程就是這樣。
-
實現(xiàn)
getFileFun
功能分析一下這個文件具體要做什么
循環(huán)讀取文件,直到將所有文件查找完,將圖片資源過濾出來,讀取文件要異步執(zhí)行,如何知道何時讀取完文件呢,這里用
promise
實現(xiàn),這里僅僅實現(xiàn)了單層文件的讀取
,因為發(fā)布到公司內(nèi)部的npm,請見諒。 聰明的你這里想想如何遞歸實現(xiàn)呢?getFileFun
: 應(yīng)該先讀取完文件,才能將圖片返回,所以異步收集器應(yīng)該在后面執(zhí)行。具體代碼如下:
const fs = require('fs').promises; const path = require('path'); const excludeDir = ['node_modules','package.json','index.html']; const excludeImg = ['png','jpg','svg','webp']; let imgPromiseArr = []; // 收集讀取圖片,作為一個異步收集器 async function readAllFile(filePath) { // 循環(huán)讀文件 const data = await fs.readdir(filePath) await dirEach(data,filePath); } async function handleIsImgFile(filePath,file) { const fileExt = file.split('.'); const fileTypeName = fileExt[fileExt.length-1]; if(excludeImg.includes(fileTypeName)) { // 將圖片丟入異步收集器 imgPromiseArr.push(new Promise((resolve,reject) => { resolve(`${filePath}${file}`) })) } } async function dirEach(arr=[],filePath) { // 循環(huán)判斷文件 for(let i=0;i<arr.length;i++) { let fileItem = arr[i]; const basePath = `${filePath}${fileItem}`; const fileInfo = await fs.stat(basePath) if(fileInfo.isFile()) { await handleIsImgFile(filePath,fileItem) } } } async function getFileFun() { // 將資源返回給調(diào)用使用 await readAllFile('./'); return await Promise.all(imgPromiseArr); } module.exports = { getFileFun }
登錄后復(fù)制 -
實現(xiàn)
handleHtml
這里讀取 test-read-img
的html文件,并替換。
const fs = require('fs').promises; const path = require('path'); const createImgs = (images=[]) => { return images.map(i => { return `<div class='img-warp'> <div class='img-item'> <img src='${i}' /> </div> <div class='img-path'>文件路徑 <span class='path'>${i}</span></div> </div>` }).join(''); } async function handleHtml(images=[]) { const template = await fs.readFile(path.join(__dirname,'template.html'),'utf-8') const targetHtml = template.replace('%--%',` ${createImgs(images)} `); return targetHtml; } module.exports = { handleHtml }
-
實現(xiàn)
createServer
這里讀取html 文件,并返回給服務(wù)器。 這里僅僅實現(xiàn)了對
png
的文件的展示,對于其他類型的圖片如何支持呢,這里提示一下對content-type
進行處理。
const http = require('http'); const fs = require('fs').promises; const path = require('path'); const open = require('open'); const createServer =(html) => { http.createServer( async (req,res) => { const fileType = path.extname(req.url); let pathName = req.url; if(pathName === '/favicon.ico') { return; } let type = '' if(fileType === '.html') { type=`text/html` } if(fileType === '.png') { type='image/png' } if(pathName === '/') { res.writeHead(200,{ 'content-type':`text/html;charset=utf-8`, 'access-control-allow-origin':"*" }) res.write(html); res.end(); return } const data = await fs.readFile('./' + pathName ); res.writeHead(200,{ 'content-type':`${type};charset=utf-8`, 'access-control-allow-origin':"*" }) res.write(data); res.end(); }).listen(3004,() => { console.log('project is run: http://localhost:3004/') open('http://localhost:3004/') }); } module.exports = { createServer }
效果