Table of Contents
Requirements analysis
2 Integrate into other projects
3 Reading the file
Thinking
Home Web Front-end JS Tutorial Node practical learning: Browser preview all pictures of the project

Node practical learning: Browser preview all pictures of the project

Jan 06, 2023 pm 09:00 PM
front end node.js

Node practical learning: Browser preview all pictures of the project

In actual front-end project development, there will be such a scenario. Every time a new picture is introduced, I don’t know whether this resource has been referenced, so I will click on the resources where the pictures are stored to look at them one by one. The actual problem is:

  • 1. The pictures are not placed in one directory. They may exist anywhere and are difficult to find

  • 2 .Time consuming and laborious

  • 3. Image resources may be introduced repeatedly

If you have the ability, list the project image resources together for viewing , and making it easy to see the introduction path will greatly save the physical work of development.

If you want to have such an ability, what should you consider?

Requirements analysis

  • ## can be integrated into any front-end project, then it requires an

    npm package

  • Read the file, analyze which pictures are, and write the picture resources into the html file through the

    img tag

  • Create a server , render the html

This needs to be achieved with the help of Node, which needs to be used

fs path http module. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]

implementation

##1 Implement a publishable npm package

    Create a project
  • npm init

    The package name is

    test-read- img

  • Add the following code to package.json
  •     "bin": {
          "readimg": "./index.js"
        },
    Copy after login
    In the entry file index.js Add test code
  • The meaning is that this file is an executable node file

      #!/usr/bin/env node
      
      console.log('111')
    Copy after login

  • Link the current module to the global node_modules module for easy debugging
  • Execute

    npm link

    Execute

    readimg

    and you will see the output 111

    Now you have realized using npm through the command After using the package, when the project installs the package and configures the execution command, the designed npm package can be executed in other projects, and this will be implemented later

      "scripts": {
       "test": "readimg"
     },
    Copy after login

2 Integrate into other projects

Create a test project and execute
    npm init
  • Integrate the test package into the current Project, execute
  • npm link test-read-img
  • Configuration execution command
  •   "scripts": {  
       "test": "readimg"
     },
    Copy after login
  • Execution
npm run test

You can see that the current project executes the code of the package that reads the file. Now only 111 is output, which is still far away from reading the file. Let’s implement reading the file

3 Reading the file

In the
    test-read-img
  • project, declare an execution function and execute it.
      #!/usr/bin/env node
      const init = async () => {
          const readFiles = await getFileFun();
          const html =  await handleHtml(readFiles);
          createServer(html);
      }
    
      init();
    Copy after login
  • Here is an explanation of the functions of each function

getFileFun

: Read the project file and return the read image file path. No image resources are required here. The reason will be explained later.

handleHtml

: Read the template html file, and generate a new html file by carrying the image resources through img.

createServer

: Place the generated html on the server and render it. The main process is like this.

    Implementation
  • getFileFun

    FunctionAnalyze what exactly this file is supposed to do

    Loop through the files until all files are After searching, filter out the image resources and read the file asynchronously. How do you know when the file has been read? This is implemented using

    promise

    . Here, only single-layer file reading is implemented. , please forgive me because it is published to npm within the company. If you are smart, think about how to implement it recursively?

    getFileFun

    : The file should be read first before the image can be returned, so the asynchronous collector should be executed later. The specific code is as follows:

        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(&#39;./&#39;);
            return await Promise.all(imgPromiseArr);
         }
    
        module.exports = {
            getFileFun
        }
    Copy after login

  • Implementation
  • handleHtml

    ##Read here
  • test -read-img
html file and replace it.

    const fs = require(&#39;fs&#39;).promises;
   const path = require(&#39;path&#39;);

   const createImgs = (images=[]) => {
       return images.map(i => {
           return `<div class=&#39;img-warp&#39;> 
              <div class=&#39;img-item&#39;>  <img  src="/static/imghw/default1.png"  data-src="https://img.php.cn/upload/article/000/000/024/2bbaed968e5cea05cb549ca3b7d46b6d-0.png"  class="lazy"   src=&#39;${i}&#39; / alt="Node practical learning: Browser preview all pictures of the project" > </div>
              <div class=&#39;img-path&#39;>文件路径 <span class=&#39;path&#39;>${i}</span></div>
            </div>`
       }).join(&#39;&#39;);
   }

   async function handleHtml(images=[]) {
       const template =   await fs.readFile(path.join(__dirname,&#39;template.html&#39;),&#39;utf-8&#39;)
       const targetHtml = template.replace(&#39;%--%&#39;,`
        ${createImgs(images)}
       `);
      return targetHtml;
   }

   module.exports = {
    handleHtml
   }
Copy after login

Implementation
    createServer
  • Read the html file here and return it to the server. This only implements the display of png

    files. How to support other types of pictures? Here is a reminder to process

    content-type.

      const http = require(&#39;http&#39;);
    const fs = require(&#39;fs&#39;).promises;
    const path = require(&#39;path&#39;);
    const open = require(&#39;open&#39;);
    
    const createServer =(html) => {
      http.createServer( async (req,res) => {
          const  fileType = path.extname(req.url);
          let pathName = req.url;
          if(pathName === &#39;/favicon.ico&#39;) {
            return;
          }
          let type = &#39;&#39;
          if(fileType === &#39;.html&#39;) {
              type=`text/html`
          }
          if(fileType === &#39;.png&#39;) {
             type=&#39;image/png&#39;
          }
          if(pathName === &#39;/&#39;) {
              res.writeHead(200,{
                  &#39;content-type&#39;:`text/html;charset=utf-8`,
                  &#39;access-control-allow-origin&#39;:"*"
              })
                res.write(html);
                res.end();
                return
          }
          const data = await fs.readFile(&#39;./&#39; + pathName );
          res.writeHead(200,{
              &#39;content-type&#39;:`${type};charset=utf-8`,
              &#39;access-control-allow-origin&#39;:"*"
          })
          res.write(data);
          res.end();
          
      }).listen(3004,() => {
       console.log(&#39;project is run: http://localhost:3004/&#39;)
      open(&#39;http://localhost:3004/&#39;)
      });
    
     
    }
    
    module.exports = {
      createServer
    }
    Copy after login
  • Effect

The above is the implementation process, execute npm run test

and you can see the browser execution in

http://localhost:3004/, the effect is as follows:

##PublishNode practical learning: Browser preview all pictures of the project

##npm login

npm publish

Thinking

  • Why read files asynchronously?

    Because js is single-threaded, if you read the file synchronously, it will get stuck there and cannot execute anything else.

  • Why use Promise to collect images

    Because we don’t know when the file has been read, and we can use it when the asynchronous reading is completedPromise.all Overall processing

  • Why not read the new html file and return the result directly to the browser?

    If you put the converted html into the test-read-img file, the image resources must also be generated in the current directory, otherwise the html will be read The equivalent path resource cannot be found because the resources are in the using project. At the end, the image resources must be deleted, which also increases the complexity;

    If you write the converted html into the usage project, you can use the image directly path, and can be loaded correctly, but this will add an html file, which needs to be deleted when the program exits. If you forget to delete it, it may be submitted to the remote location by the developer, causing pollution. The preview provided should be harmless of. Neither approach is advisable. Therefore, returning the html resource directly and letting it load the relative target project path will not have any impact.

For more node-related knowledge, please visit: nodejs tutorial!

The above is the detailed content of Node practical learning: Browser preview all pictures of the project. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

How to use Go language for front-end development? How to use Go language for front-end development? Jun 10, 2023 pm 05:00 PM

With the development of Internet technology, front-end development has become increasingly important. Especially the popularity of mobile devices requires front-end development technology that is efficient, stable, safe and easy to maintain. As a rapidly developing programming language, Go language has been used by more and more developers. So, is it feasible to use Go language for front-end development? Next, this article will explain in detail how to use Go language for front-end development. Let’s first take a look at why Go language is used for front-end development. Many people think that Go language is a

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

C# development experience sharing: front-end and back-end collaborative development skills C# development experience sharing: front-end and back-end collaborative development skills Nov 23, 2023 am 10:13 AM

As a C# developer, our development work usually includes front-end and back-end development. As technology develops and the complexity of projects increases, the collaborative development of front-end and back-end has become more and more important and complex. This article will share some front-end and back-end collaborative development techniques to help C# developers complete development work more efficiently. After determining the interface specifications, collaborative development of the front-end and back-end is inseparable from the interaction of API interfaces. To ensure the smooth progress of front-end and back-end collaborative development, the most important thing is to define good interface specifications. Interface specification involves the name of the interface

Can golang be used as front-end? Can golang be used as front-end? Jun 06, 2023 am 09:19 AM

Golang can be used as a front-end. Golang is a very versatile programming language that can be used to develop different types of applications, including front-end applications. By using Golang to write the front-end, you can get rid of a series of problems caused by languages ​​​​such as JavaScript. For example, problems such as poor type safety, low performance, and difficult to maintain code.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

How to implement instant messaging on the front end How to implement instant messaging on the front end Oct 09, 2023 pm 02:47 PM

Methods for implementing instant messaging include WebSocket, Long Polling, Server-Sent Events, WebRTC, etc. Detailed introduction: 1. WebSocket, which can establish a persistent connection between the client and the server to achieve real-time two-way communication. The front end can use the WebSocket API to create a WebSocket connection and achieve instant messaging by sending and receiving messages; 2. Long Polling, a technology that simulates real-time communication, etc.

See all articles