在前端實際專案開發中,會有這樣一種場景。每次引入新的圖片,並不知道這個資源是否被引用過,所以會點開存放圖片的資源一個個去看。實際問題是:
1.圖片並不是放到一個目錄下的,可能存在任何的地方,不好找
2 .費時間,費力
3.可能會重複引入圖片資源
如果有個能力,將項目圖片資源羅列到一起查看,並方便看到引入路徑的話,就會大大節約開發的體力活。
如果要做這樣的能力,該考慮什麼呢?
需求分析
可以整合到任何前端專案中,那就要求是個
npm套件
讀取文件,分析哪些是圖片,將圖片資源透過
img標籤
寫入到html檔案中建立一個伺服器,將html渲染出來
這就需要藉助Node來實現,需要用到的fs
path
http
模組。 【相關教學推薦:nodejs影片教學、程式設計教學】
#實作
##1實作可發佈npm套件
- 建立一個專案
npm init
套件名字是test-read- img
- 在package.json 中加入下列程式碼
"bin": { "readimg": "./index.js" },
- 在入口檔index.js 中加入測試程式碼意思是這個檔案是可執行的node檔案
#!/usr/bin/env node console.log('111')
- #將目前模組連結到全域node_modules模組內,方便偵錯#執行
npm link
執行readimg
#就看到輸出111 了到此就實作了透過指令使用npm套件的使用了,當專案安裝了這個套件,並且設定執行指令,就可以在別的專案執行設計的npm套件了,後面就實作這個"scripts": { "test": "readimg" },
2 整合到別的項目
- 建立一個測試項目,執行
- npm init
- npm link test-read-img
"scripts": { "test": "readimg" },
npm run test
#3 讀取檔案
在test-read-img
專案中,宣告一個執行函數,並執行.
#!/usr/bin/env node const init = async () => { const readFiles = await getFileFun(); const html = await handleHtml(readFiles); createServer(html); } init();
這裡解釋一下,各函數作用
getFileFun : 讀取項目文件,並將讀取的圖片文件路徑返回,這裡不需要圖片資源,後面解釋為什麼。 handleHtml
img
承載 產生新的html檔。-
createServer
主流程就是這樣。: 將產生的html ,放到伺服器下去渲染出來。
分析這個文件具體要做什麼實作
getFileFun功能
實現,這裡僅僅實現了循環讀取文件,直到將所有文件查找完,將圖片資源過濾出來,讀取文件要異步執行,如何知道何時讀取完文件呢,這裡用
promise單層文件的讀取
,因為發佈到公司內部的npm,請見諒。聰明的你在這裡想想如何遞歸實現? -
getFileFun
具體程式碼如下:: 應該先讀取完文件,才能將圖片傳回,所以非同步收集器應該在後面執行。
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) { // 循环读文件 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) { // 循环判断文件 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() { // 将资源返回给调用使用 await readAllFile('./'); return await Promise.all(imgPromiseArr); } module.exports = { getFileFun }
實作
handleHtml
-
的html文件,並替換。這裡讀取
test -read-imgconst 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="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/024/2bbaed968e5cea05cb549ca3b7d46b6d-0.png?x-oss-process=image/resize,p_40" class="lazy" src='${i}' / alt="Node實戰學習:瀏覽器預覽專案所有圖片" > </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 }
實作
createServer
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 }效果
以上就是實作過程,執行一下
就可以看到瀏覽器執行在http://localhost:3004/, 效果如下:
npm publish
思考
-
#為什麼要用非同步讀取檔案?
因為js是單線程,同步讀取檔的話會卡在那裡,不能執行其他了。
-
為什麼要用Promise 收集圖片
因為不知道什麼時候讀取完文件,當非同步讀取完再用
Promise.all
整體處理 -
為什麼不讀取新的html文件,而將結果直接傳回瀏覽器?
如果將轉換後
html放到
test-read-img
文件,就必須將圖片資源也要產生在目前目錄,不然html 讀取的相當路徑資源是找不到的,因為資源都在使用專案中。結束的時候還要將圖片資源刪除,這也無形增加了複雜度;如果將轉換後的
html 寫入放到使用項目
中,這樣就可以直接用圖片的路徑,並能正確加載,但是這樣會多了一個html文件,程序退出的時候還要刪除這個,如果忘記刪除了,就可能被開發者提交到遠程,造成污染,提供的預覽應該是無害的。這兩種方式都不可取。因此直接返回html資源,讓它載入相對目標專案路徑,不會產生任何影響。
更多node相關知識,請造訪:nodejs 教學!
以上是Node實戰學習:瀏覽器預覽專案所有圖片的詳細內容。更多資訊請關注PHP中文網其他相關文章!

javaandjavascriptaredistinctlanguages:javaisusedforenterpriseandmobileapps,while javascriptifforInteractiveWebpages.1)JavaisComcompoppored,statieldinglationallyTypted,statilly tater astrunsonjvm.2)

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版
中文版,非常好用

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)