Renaming files using node.js

前端 未结 4 1257
你的背包
你的背包 2020-12-02 14:14

I am quite new in using JS, so I will try to be as specific as I can :)

  • I have a folder with 260 .png files with different country names: Afghanistan.

相关标签:
4条回答
  • 2020-12-02 14:39

    For linux/unix OS, you can use the shell syntax

    const shell = require('child_process').execSync ; 
    
    const currentPath= `/path/to/name.png`;
    const newPath= `/path/to/another_name.png`;
    
    shell(`mv ${currentPath} ${newPath}`);
    

    That's it!

    0 讨论(0)
  • 2020-12-02 14:41
    1. fs.readdir(path, callback)
    2. fs.rename(old,new,callback)

    Go through http://nodejs.org/api/fs.html

    One important thing - you can use sync functions also. (It will work like C program)

    0 讨论(0)
  • 2020-12-02 14:49

    For synchronous renaming use fs.renameSync

    fs.renameSync('/path/to/Afghanistan.png', '/path/to/AF.png');
    
    0 讨论(0)
  • 2020-12-02 14:50

    You'll need to use fs for that: http://nodejs.org/api/fs.html

    And in particular the fs.rename() function:

    var fs = require('fs');
    fs.rename('/path/to/Afghanistan.png', '/path/to/AF.png', function(err) {
        if ( err ) console.log('ERROR: ' + err);
    });
    

    Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.

    fs.readFile('/path/to/countries.json', function(error, data) {
        if (error) {
            console.log(error);
            return;
        }
    
        var obj = JSON.parse(data);
        for(var p in obj) {
            fs.rename('/path/to/' + obj[p] + '.png', '/path/to/' + p + '.png', function(err) {
                if ( err ) console.log('ERROR: ' + err);
            });
        }
    });
    

    (This assumes here that your .json file is trustworthy and that it's safe to use its keys and values directly in filenames. If that's not the case, be sure to escape those properly!)

    0 讨论(0)
提交回复
热议问题