Node怎么实现浏览器预览项目所有图片

发布时间:2023-01-09 10:36:13 作者:iii
来源:亿速云 阅读:112

本文小编为大家详细介绍“Node怎么实现浏览器预览项目所有图片”,内容详细,步骤清晰,细节处理妥当,希望这篇“Node怎么实现浏览器预览项目所有图片”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

在前端实际项目开发中,会有这样一种场景。每次引入新的图片,并不知道这个资源是否被引用过,所以会点开存放图片的资源一个个去看。实际问题是:

如果有个能力,将项目图片资源罗列到一起查看,并方便看到引入路径的话,就会大大节约开发的体力活。

需求分析

这就需要借助Node来实现,需要用到的 fs path http 模块。

实现

1 实现可发布npm包

    "bin": {
      "readimg": "./index.js"
    },

2 集成到别的项目

  "scripts": {  
   "test": "readimg"
 },

执行npm run test

就能看到当前项目执行了读取文件的包的代码了。 现在只输出了 111距离读取文件还很远,下面来实现读取文件

3 读取文件

  #!/usr/bin/env node
  const init = async () => {
      const readFiles = await getFileFun();
      const html =  await handleHtml(readFiles);
      createServer(html);
  }

  init();

这里解释一下 ,各函数作用

getFileFun: 读取项目文件,并将读取的图片文件路径返回,这里不需要图片资源,后面解释为什么。

handleHtml: 读取模版html文件, 将图片资源通过 img 承载 生成新的html文件。

createServer : 将生成的html ,放到服务器下去渲染出来。

主流程就是这样。

这里读取 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
   }

  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
}

效果

以上就是实现过程,执行一下 npm run test就可以看到浏览器执行在http://localhost:3004/, 效果如下:

Node怎么实现浏览器预览项目所有图片

发布

npm login

npm publish

思考

读到这里,这篇“Node怎么实现浏览器预览项目所有图片”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. vscode导入node项目的方法
  2. vscode调试node的方

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

node

上一篇:go语言有while吗

下一篇:Angular中的依赖注入如何使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》