Problem: There are a large number of image files in folder A. You need to replace the image in A with another image, but the name remains the same.
The manual method is as follows:
1) Open the image in the browser -> 2) Save as -> 3) Target folder -> 4) Find an image -> 5) Replace -> 6) OK
Then, repeat step 2) and the subsequent steps. It will miss or repeat accidentally.
It's so troublesome, how to use node.js to handle the changes? The code is as follows:
var fs=require('fs'), cp=require('child_process');var url='Moriarty.jpg'var rs=fs.readFileSync(url,{encoding:'hex',flag:'r'})var write=(e)=>{ fs.writeFileSync(e,rs,{encoding:'hex',flag:'w'}) }var buf_files=cp.execSync('ls 160906/*.jpg')var arr_files=buf_files.toString().trim().split(//s+/)arr_files.forEach(write)It can also be done using glob and fs modules: the code is as follows:
var glob=require('glob'), fs=require('fs')var url='Moriarty.jpg'var rs=fs.readFileSync(url,{encoding:'hex',flag:'r'})var write=(e)=>{ fs.writeFileSync(e,rs,{encoding:'hex',flag:'w'}) }glob('160906/*.jpg',(err,files)=>{ files.forEach(write) })The effect is as follows:
Original image of the file:
New file picture: (The image file name has not changed)
The above method of implementing batch replacement pictures of Node.js reading and writing files is the entire content shared by the editor. I hope it can give you a reference and I hope you can support Wulin.com more.