node.jsfsasar

Copy asar file using NodeJS file system (fs)


My goal is to copy a .asar file using NodeJS's file system. I have a file path and need to copy the .asar file to another destination.

Example of file path:

C:/Users/redacted/Documents/ExampleElectronApp/example.asar

I need to copy this file (archive) to another directory.

Previously I copied this with a walk and copy function but it ended up creating a directory named filename.asar instead of an actual file named filename.asar This function seems to work on all other files and folders correctly (except for .asar archives).

What I have tried

1: Copying the archive using read and write streams.

var fs = require('fs');
fs.createReadStream('C:/Users/redacted/Documents/redacted/node_modules/electron-prebuilt/dist/resources/default_app.asar').pipe(fs.createWriteStream('C:/Users/redacted/Desktop/test.asar'));

This ended up giving an error: Error #1

It says this file is not found but I can assure you, copying the source path does lead me to the .asar file.

2: Using the asar requirement to create a package.

var fs = require('fs');
var asar = require('asar');

asar.createPackage('C:/Users/redacted/Documents/redacted/node_modules/electron-prebuilt/dist/resources/default_app.asar', 'C:/Users/redacted/Desktop/test.asar', function() {
  console.log('done.');
})

While this function does log the correct 'done' message, it seems that the copy was unsucessful. No new files or folders are shown in the destination directory.

Thank you all in advance.


Solution

  • The way I ended up succeeding this was by renaming the .asar files then renaming them back after I copied them. Here is my final source for copying .asar files:

    var filePathSource = path.join(__dirname, 'default_app.asar')
    var filePathTarget = path.join(__dirname, 'test.txt')
    
    var filePathSourceNew = filePathSource.slice(0, -5) + ".txt";
    console.log(filePathSourceNew);
    
    fs.rename(filePathSource, filePathSourceNew, function(err) {
        if (err) {
          console.log('ERROR: ' + err);
        } else {
          var stream = fs.createReadStream(filePathSourceNew).pipe(fs.createWriteStream(filePathTarget));
          stream.on('finish', function () {
            fs.rename(filePathSourceNew, filePathSource, function(err) {
                if (err) {
                  console.log('ERROR: ' + err);
                } else {
                  fs.rename(filePathTarget, filePathTarget.slice(0, -4) + ".asar", function(err) {
                      if (err) {
                        console.log('ERROR: ' + err);
                      } else {
                        console.log("Complete Asar Copy");
                      }
                  });
                }
            });
          });
        }
    });