As a front end, in the process of project development, when you need to transfer all the pictures used in some files of one project to another project, if you do not want to copy the whole picture file, you will usually choose to search one picture after another and then manually copy it. If the page uses a lot of images, it’s slow as a turtle. Therefore, I chose to use nodeJs implementation to quickly generate local images used in project files.

Note: This code example only works on Windows systems. If you want to adapt it to other systems, modify the output path.

First Kangkang final effect:

You can see that the terminal running the command produces a file of all the local images used in the file.

PS: nodeJs can do a lot of things with it.

1. Initialization

Create a new file copyimg.js and initialize the code:

    #!/usr/bin/env node

    // Import modules
    const path = require('path');
    const fs = require('fs');

    var args = process.argv.splice(2);
    let curPath = args[0];  // The absolute path to the project file where you want to get the image
    var outputPath = "c:\\Users\\Administrator\\Desktop\\copyimg\\";  // Image file input path
Copy the code

As above, we will run Node copyimg [project filename] on the terminal to generate the image file and save the resulting image file to the copyimg folder on the computer desktop.

2. Obtain the absolute path of the image file

Local images in a project are usually referenced in relative paths, for example: “.. /.. /images/button.png”, we need to convert them all to absolute paths. The following re is used:

/ (? <quotes>['"]) (? 
      
       [-\w/.]+?) \. (? 
       
        png|jpg)\k
        
         /ug
        
       
      Copy the code

This regex circumvents image links uploaded to the CDN, and while it doesn’t give much consideration to backtracking, it’s enough to be useful and not the point here.

    let imgList = [];

    toReadImg();

    // Get the absolute img path
    function getImgPath(imgRelativePath = "") {
        return path.resolve(path.dirname(curPath), imgRelativePath);
    }

    function toReadImg() {
        fs.readFile(curPath, { encoding: 'utf-8' }, (err, data) = > {
            data.replace(/ (? 
      
       ['"])(? 
       
        [-\w/.]+?) \. (? 
        
         png|jpg)\k
         
          /ug
         
        
       
      .(. args) = > {
                let groups = args[args.length -1];
                let { content, suffix } = groups;
                let imgPath = getImgPath(content + '. ' + suffix);
                imgList.push(imgPath);
            });

            console.log("imgList", imgList);
        });
    }
Copy the code

At this point, we have the absolute path to all the local images. After running, the terminal will print out the array imgList containing the absolute path of the image.

3. Obtain the root path of all image files and project files

This step is necessary because we are going to copy the image to our custom path, called outputPath.

    // Get the longest public prefix path
    getCommonPath = function getCommonPath (path1 = ' ', path2 = ' '. rest) {
        path1 = path1.replace(/ [^ \ \] + $/.' ');
        if(! path2)return path1;
        path2 = path2.replace(/ [^ \ \] + $/.' ');

        let base = ' ';
        for (let i = 0; i < path1.length && i < path2.length; i++) {
          if (path1[i] === path2[i]) {
            base += path2[i]
          } else {
            break}}if (rest.length) {
          returngetCommonPath(base, ... rest); }return base
    };

    letcommonPath = getCommonPath(curPath, ... imgList);console.log('commonPath: ', commonPath);
Copy the code

4. Generate images tooutputPathCorresponding folder

    imgList.forEach(imgPath= > {
        writeImg(imgPath, imgPath.replace(commonPath, outputPath));
    })

    // Add a slash to the end of the path
    function addSlash(pathStr) {
        if (pathStr[pathStr.length - 1] != "\ \") {
            pathStr += "\ \"
        }
        return pathStr
    }

    // Rollback if a folder path does not exist
    function handleDirReturn(folder, dirList) {
        if (dirList.length) {
            folder = addSlash(folder) + dirList.pop();
            mkdirFolder(folder, dirList)
        }
    }

    // Create a folder
    function mkdirFolder(folder, dirList = []) {
        try {
            fs.accessSync (folder);
            handleDirReturn(folder, dirList);
        } catch(error) {
            try {
                fs.mkdirSync(folder, 0777);
                handleDirReturn(folder, dirList);
            } catch(err) {
                let newPath = path.resolve(folder, '.. ');
                dirList.push(path.basename(folder));
                let num = 0;
                newPath.replace(/\\/g.() = > {
                    ++num;
                })
                if (num > 1) { mkdirFolder(newPath, dirList); }}}}// Generate the image
    function writeImg(oldPath, newPath) {
        let imgDir = path.resolve(newPath, '.. ');
        mkdirFolder(imgDir);
        fs.readFile(oldPath, function(err,originBuffer) {            // Read the image position
            fs.writeFile(newPath, originBuffer, function(err){      // Generate the image
                if (err) {
                    console.log(err) } }); })}Copy the code

At this point, the functionality is implemented. Of course, we can add a little code to make it support custom output paths:

    if (args[1]) {
        outputPath = args[1];
    }
    outputPath = addSlash(outputPath);
Copy the code

In this way, you can copy the pictures of project A directly to the folder of project B, in one step.

The complete code is as follows:

    #!/usr/bin/env node
    const path = require('path');
    const fs = require('fs');

    var args = process.argv.splice(2);
    let curPath = args[0];
    var outputPath = "c:\\Users\\Administrator\\Desktop\\copyimg\\";  // Modify as required
    let imgList = [];

    if (curPath) {
        if (args[1]) {
            outputPath = args[1];
        }
        outputPath = addSlash(outputPath);

        console.log('File absolute path:', curPath);
        console.log('File output path:', outputPath);

        mkdirFolder(outputPath);

        toReadImg();
    } else {
        console.log('Please enter the absolute file path');
    }

    // Get the absolute img path
    function getImgPath(imgRelativePath = "") {
        return path.resolve(path.dirname(curPath), imgRelativePath);
    }

    function toReadImg() {
        fs.readFile(curPath, { encoding: 'utf-8' }, (err, data) = > {
            if (err) {
                console.log(`err`, err);
            }
            data.replace(/ (? 
      
       ['"])(? 
       
        [-\w/.]+?) \. (? 
        
         png|jpg)\k
         
          /ug
         
        
       
      .(. args) = > {
                var groups = args[args.length -1];
                let { content, suffix } = groups;
                let imgPath = getImgPath(content + '. ' + suffix);
                imgList.push(imgPath);
            });
            letcommonPath = getCommonPath(curPath, ... imgList);// console.log('commonPath: ', commonPath);

            imgList.forEach(item= >{ writeImg(item, item.replace(commonPath, outputPath)); })}); }function handleDirReturn(folder, dirList) {
        if (dirList.length) {
            // console.log('handleDirReturn: ', folder, [...dirList]);
            folder = addSlash(folder) + dirList.pop();
            mkdirFolder(folder, dirList)
        }
    }
    function mkdirFolder(folder, dirList = []) {
        // if (! dirList.length) {
        // console.log('mkdirFolder: ', folder, [...dirList]);
        // }
        try {
            fs.accessSync (folder);
            handleDirReturn(folder, dirList);
        } catch(error) {
            try {
                fs.mkdirSync(folder, 0777);
                handleDirReturn(folder, dirList);
            } catch(err) {
                let newPath = path.resolve(folder, '.. ');
                dirList.push(path.basename(folder));
                let num = 0;
                newPath.replace(/\\/g.() = > {
                    ++num;
                })
                if (num > 1) { mkdirFolder(newPath, dirList); }}}}// Generate the image
    function writeImg(oldPath, newPath) {
        let imgDir = path.resolve(newPath, '.. ');
        mkdirFolder(imgDir);
        fs.readFile(oldPath, function(err,originBuffer) {            // Read the image position
            fs.writeFile(newPath, originBuffer, function(err){      // Generate the image
                if (err) {
                    console.log(err) } }); })}// Get the longest public prefix path
    getCommonPath = function getCommonPath (path1 = ' ', path2 = ' '. rest) {
        path1 = path1.replace(/ [^ \ \] + $/.' ')
        if(! path2)return path1
        path2 = path2.replace(/ [^ \ \] + $/.' ')

        let base = ' '
        for (let i = 0; i < path1.length && i < path2.length; i++) {
          if (path1[i] === path2[i]) {
            base += path2[i]
          } else {
            break}}if (rest.length) {
          returngetCommonPath(base, ... rest) }return base
    };

    // Add a trailing slash
    function addSlash(pathStr) {
        if (pathStr[pathStr.length - 1] != "\ \") {
            pathStr += "\ \"
        }
        return pathStr
    }
Copy the code