nodejs calls the cmd command to copy directories

  • 2020-06-03 05:50:54
  • OfStack

In my work, I always need to copy some official websites and replace some internal information. Previously, I did this manually or through the self-written firefox extension.

Now that we have nodejs in the front, why not write nodejs as a 1 key

1. Copy the directory

When copying a file, it is not successful to create a file directory that does not exist. The parent directory exists. (nodejs API contact time is not long. If there is any mistake, thank you for correcting me.)

In this way, when the file is written, it can detect whether the directory under 1 exists, and determine the parent directory if it does not exist, and then the level-1 directory will be created back, and then the file can be copied


var dirCache = {};// Cache reduction judgment 
function makedir (pathStr, callback) {
  if (dirCache[pathStr] == 1) {
    callback();
  } else {
    fs.exists(pathStr, function (exists) {
      if (exists == true) {
        dirCache[pathStr] == 1;
        callback();
      } else {
        makedir(path.dirname(pathStr), function () {
          fs.mkdir(pathStr, function () {
            dirCache[pathStr] == 1;
            callback();
          })
        });
      }
    })
  }
};

2. Later, I still considered the CMD command "xcopy" to achieve, but tried a good 9, direct execution, but 1 is not straight, there is a solution, welcome correction


var exec = require('child_process').exec;
  exec('xcopy D:\\WORK_new\\odinQuest D:\\WORK_new\\newGame /s /e /Q /Y /I',
    function (error, stdout, stderr) {
      if (error !== null) {
        //console.log('exec error: ' + error);
      }
    
  });

Later, by writing the CMD command to a file, the call call is done.


fs.writeFile('xcopy.bat', cmdstr, function (err) {
  if (err) throw err;
  var exec = require('child_process').exec;
  exec('call "'+process.cwd()+'/xcopy.bat',
    function (error, stdout, stderr) {
      if (error !== null) {
        //console.log('exec error: ' + error);
      }
    
  });
}); 

Well, the code is written as such, is a step by step asynchronous nesting, not put out, save the joke

This is the end of this article, I hope you enjoy it.


Related articles: