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
fs
path
http module. [Related tutorial recommendations:
nodejs video tutorial, Programming teaching]
implementation
##1 Implement a publishable npm package
- Create a project
- npm init
test-read- imgThe package name is
Add the following code to package.json -
"bin": { "readimg": "./index.js" },
- 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')
Link the current module to the global node_modules module for easy debugging -
Execute
npm link
readimgExecute
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" },
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" },
Execution
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();
Here is an explanation of the functions of each function
: Read the project file and return the read image file path. No image resources are required here. The reason will be explained later.
: Read the template html file, and generate a new html file by carrying the image resources through img
.
: Place the generated html on the server and render it. The main process is like this.
- Implementation
- getFileFun
Function
Analyze 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
getFileFunsingle-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?: 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('./'); return await Promise.all(imgPromiseArr); } module.exports = { getFileFun }
Implementation - handleHtml
##Read here test -read-img
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="/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 practical learning: Browser preview all pictures of the project" > </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 }
Implementation - createServer
-
files. How to support other types of pictures? Here is a reminder to processRead the html file here and return it to the server. This only implements the display of
pngcontent-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 }
Effect
The above is the implementation process, execute npm run test
and you can see the browser execution inhttp://localhost:3004/, the effect is as follows:
##Publish
##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 completed
Promise.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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
