亚洲最大看欧美片,亚洲图揄拍自拍另类图片,欧美精品v国产精品v呦,日本在线精品视频免费

  • 站長(zhǎng)資訊網(wǎng)
    最全最豐富的資訊網(wǎng)站

    Node實(shí)戰(zhàn)學(xué)習(xí):瀏覽器預(yù)覽項(xiàng)目所有圖片

    Node實(shí)戰(zhàn)學(xué)習(xí):瀏覽器預(yù)覽項(xiàng)目所有圖片

    在前端實(shí)際項(xiàng)目開發(fā)中,會(huì)有這樣一種場(chǎng)景。每次引入新的圖片,并不知道這個(gè)資源是否被引用過(guò),所以會(huì)點(diǎn)開存放圖片的資源一個(gè)個(gè)去看。實(shí)際問(wèn)題是:

    • 1.圖片并不是放到一個(gè)目錄下的,可能存在任何的地方,不好查找

    • 2.費(fèi)時(shí)間,費(fèi)力

    • 3.可能會(huì)重復(fù)引入圖片資源

    如果有個(gè)能力,將項(xiàng)目圖片資源羅列到一起查看,并方便看到引入路徑的話,就會(huì)大大節(jié)約開發(fā)的體力活。

    如果要做這樣的能力,應(yīng)該考慮什么呢?

    需求分析

    • 可以集成到任何前端項(xiàng)目中,那就要求是個(gè)npm包

    • 讀取文件,分析哪些是圖片,將圖片資源通過(guò)img標(biāo)簽寫入到html文件中

    • 創(chuàng)建一個(gè)服務(wù)器,將html渲染出來(lái)

    這就需要借助Node來(lái)實(shí)現(xiàn),需要用到的 fs path http 模塊?!鞠嚓P(guān)教程推薦:nodejs視頻教程、編程教學(xué)】

    實(shí)現(xiàn)

    1 實(shí)現(xiàn)可發(fā)布npm包

    • 創(chuàng)建一個(gè)項(xiàng)目 npm init

      包名字是 test-read-img

    • 在package.json 中加入如下代碼

        "bin": {       "readimg": "./index.js"     },
    登錄后復(fù)制

    • 在入口文件index.js 中加入測(cè)試代碼

      含義是這個(gè)文件是可執(zhí)行的node文件

        #!/usr/bin/env node      console.log('111')
      登錄后復(fù)制

    • 將當(dāng)前模塊鏈接到全局node_modules模塊內(nèi),方便調(diào)試

      執(zhí)行 npm link

      執(zhí)行 readimg

      就看到輸出111 了

      到此就實(shí)現(xiàn)了通過(guò)命令使用npm包的使用了,當(dāng)項(xiàng)目安裝了這個(gè)包,并配置執(zhí)行命令,就可以在別的項(xiàng)目執(zhí)行設(shè)計(jì)的npm包了,后面就實(shí)現(xiàn)這個(gè)

        "scripts": {    "test": "readimg"  },
      登錄后復(fù)制

    2 集成到別的項(xiàng)目

    • 創(chuàng)建一個(gè)測(cè)試項(xiàng)目 ,執(zhí)行 npm init
    • 將測(cè)試包集成到當(dāng)前項(xiàng)目, 執(zhí)行 npm link test-read-img
    • 配置執(zhí)行命令

      "scripts": {      "test": "readimg"  },
    登錄后復(fù)制

    執(zhí)行npm run test

    就能看到當(dāng)前項(xiàng)目執(zhí)行了讀取文件的包的代碼了。 現(xiàn)在只輸出了 111距離讀取文件還很遠(yuǎn),下面來(lái)實(shí)現(xiàn)讀取文件

    3 讀取文件

    • test-read-img 項(xiàng)目中,聲明一個(gè)執(zhí)行函數(shù),并執(zhí)行.

      #!/usr/bin/env node   const init = async () => {       const readFiles = await getFileFun();       const html =  await handleHtml(readFiles);       createServer(html);   }    init();
    登錄后復(fù)制

    這里解釋一下 ,各函數(shù)作用

    getFileFun: 讀取項(xiàng)目文件,并將讀取的圖片文件路徑返回,這里不需要圖片資源,后面解釋為什么。

    handleHtml: 讀取模版html文件, 將圖片資源通過(guò) img 承載 生成新的html文件。

    createServer : 將生成的html ,放到服務(wù)器下去渲染出來(lái)。

    主流程就是這樣。

    • 實(shí)現(xiàn)getFileFun 功能

      分析一下這個(gè)文件具體要做什么

      循環(huán)讀取文件,直到將所有文件查找完,將圖片資源過(guò)濾出來(lái),讀取文件要異步執(zhí)行,如何知道何時(shí)讀取完文件呢,這里用promise實(shí)現(xiàn),這里僅僅實(shí)現(xiàn)了單層文件的讀取 ,因?yàn)榘l(fā)布到公司內(nèi)部的npm,請(qǐng)見諒。 聰明的你這里想想如何遞歸實(shí)現(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 = []; // 收集讀取圖片,作為一個(gè)異步收集器     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ù)制

    • 實(shí)現(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    }
    登錄后復(fù)制

    • 實(shí)現(xiàn) createServer

      這里讀取html 文件,并返回給服務(wù)器。 這里僅僅實(shí)現(xiàn)了對(duì) png的文件的展示,對(duì)于其他類型的圖片如何支持呢,這里提示一下對(duì) content-type進(jìn)行處理。

      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 }
    登錄后復(fù)制

    效果

    贊(0)
    分享到: 更多 (0)
    網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)