NodeJS won't copy folder to another folder

Discussion in 'Learning Javascript' started by Hisao Shou, Aug 14, 2019.

  1. Hisao Shou

    Hisao Shou Veteran Veteran

    Messages:
    87
    Likes Received:
    13
    Hello there. I was recently working on a game which is supposed to be a "DDLC" wannabe, where files from inside the game are getting edited/copied/removed.

    I'm currently trying to figure out how to copy a whole folder to another folder from inside the game' directory.
    I have managed to simply copy files from a folder to another folder, yet I couldn't do the same with folders.

    I have tried to use different kind of functions and scripts for basic NodeJS, yet it didn't work.
    More precisely, I have tried some scripts / functions from NodeJS community to accomplish this folder copy:

    Using both Path and FS modules:
    Code:
    var fs=require("fs"),path=require("path");
    function copyFolderSync(from, to) {
        fs.mkdirSync(to);
        fs.readdirSync(from).forEach(element => {
            if (fs.lstatSync(path.join(from, element)).isFile()) {
                fs.copyFileSync(path.join(from, element), path.join(to, element));
            } else {
                copyFolderSync(path.join(from, element), path.join(to, element));
            }
        });
    }; 
    currentLoc = process.cwd(); copyFolderSync(currentLoc + '\\img\\', currentLoc + '\\save\\');
    
    Generated error: error: EEXIST: file already exists, mkdir '[censoredComputerPath]\save'

    Using shell command:
    Code:
    var sys = require('sys'),
        exec = require('child_process').exec;
    child = exec("copy -r save img", function(error, stdout, stderr) {
       sys.print("stdout: " + stdout);
       sys.print("stderr: " + stderr);
        if(error !== null) {
          console.log("exec error: " + error);
        } else {
      }
    });
    Generated error: exec error: Error: Command failed: copy -r save img

    Also I haven't tried the FS-EXTRA module as I don't know how to add it easily to the project.
    For starters I have tried to copy the save folder within the img folder of the game director, but none of these functions didn't work.

    I have ran these codes within simple common events with Script command.

    Can someone please help me with this issue?
     
    #1
  2. peq42_

    peq42_ Yeet Veteran

    Messages:
    452
    Likes Received:
    269
    Location:
    Brazil
    First Language:
    Portuguese(BR)
    Primarily Uses:
    RMMV
    try adding a few checks to the first code you posted(the one using path and fs) to make sure that it isn't trying to copy a file to a folder which already has a file with the same name(do the same for folders aswell, just to be sure).

    if that doesn't fix, try using this module(or taking a look at its code):
    https://www.npmjs.com/package/ncp
     
    #2
  3. Adventurer_inc.

    Adventurer_inc. Technically a Programmer Veteran

    Messages:
    94
    Likes Received:
    40
    Location:
    USA
    First Language:
    English
    Primarily Uses:
    RMMV
    Have you tried deleting the existing folder/file before copying over? I'm actually too keen on Javascript but in a custom language I used based on C++, overwriting is not allowed. You have to delete then copy file/folders.

    Edit: I just realized this is exactly what peq42_ implied. :D
     
    #3
  4. Hisao Shou

    Hisao Shou Veteran Veteran

    Messages:
    87
    Likes Received:
    13
    Thank you for your answer!
    I think I have found where the problem is with FS/Path code. It copies the folder content from "FROM" to "TO", instead of copying FROM to FROM.NAME + TO. I mean, if the directory exists the code won't create a new folder (with the name of FROM value) to destination.
    For example this is what worked:

    Code:
    var fs=require("fs"); path=require("path");
    function copyFolderSync(from, to) {
        fs.mkdirSync(to);
        fs.readdirSync(from).forEach(element => {
            if (fs.lstatSync(path.join(from, element)).isFile()) {
                fs.copyFileSync(path.join(from, element), path.join(to, element));
            } else {
                copyFolderSync(path.join(from, element), path.join(to, element));
            }
        });};
    currentLoc = process.cwd(); copyFolderSync(currentLoc + '\\save\\', currentLoc + '\\img\\testFolder2\\');
    ...because it created a new folder "testFolder2" in game's img folder, with all the contents of save folder.
    Unfortunately I don't know at all how to make it copy the whole folder (as entity = folder name + its content) to another location. Can someone please help me here?

    Also, I have tried the NCP but I don't have it installed, so it throws error. And unfortunately I don't know how to easily install a new module inside RPG Maker MV.
     
    #4
  5. peq42_

    peq42_ Yeet Veteran

    Messages:
    452
    Likes Received:
    269
    Location:
    Brazil
    First Language:
    Portuguese(BR)
    Primarily Uses:
    RMMV
    In NCP's case its quite easy. Download it, copy the NCP.js file to the libs folder(within the js folder) then do:

    Code:
    var ncp = require('./js/libs/ncp.js').ncp;
        ncp.limit = 16;
        ncp("origin/folder/path/", "destination/folder/path/", function (err) {
    if(err){
    //if there's an error, do something. Optional.
    }
    //the code that should execute after the folder gets copied.
    })
     
    #5
  6. Jonforum

    Jonforum Veteran Veteran

    Messages:
    1,575
    Likes Received:
    1,344
    Location:
    Canada / Qu├ębec
    First Language:
    French
    Primarily Uses:
    RMMV
    what you will maybe need, is to do it copy file data, stringify and than write again in the new folder.
    look for `writeFile` module.

    example user case on my side `create a json`, but not for your context, you will need hack.
    PHP:
        create_JSON(options) {
            const 
    _lights      = {ambientLight:false,DirectionalLight:false,PointLight:false}
            const 
    _objs        $objs.LOCAL.filter(a=>a).map(a=>a.factory);//$objs.get_list;
            
    const _background  $stage.scene.background.initializeFactory(); // factory dataValues
            
    const _sheets      = Array.from( new Set(_objs.map(dataObj=>dataObj.g._dataBaseName.value)).add(_background.g._dataBaseName.value) ) ; // Set: remove les duplicata
            
    const SYSTEM = {}; // TODO:
            ///const SYSTEM = {memoryUsage:dataValues.memoryUsage,timeElasped:PIXI.ticker.shared.lastTime / 1000, data: new Date().toDateString()};
            
    const json = { SYSTEM_lights _background_sheets_objs, };
            const 
    fs = eval("require('fs')");
            function 
    writeFile(path,content){
                
    // backup current to _old.json with replace() rename()
                
    fs.rename(`${path}`, `${path.replace(".","_OLD.")}`, function(err) {
                    if ( 
    err ) { console.log('ERROR:rename ' err) };
                    
    fs.writeFile(pathcontent'utf8', function (err) {
                        if(
    err){return console.error(path,err) }
                        
    $stage.interactiveChildren true// disable stage interactive
                        
    return console.log9("WriteFile Complette: "+path,JSON.parse(content));
                    });
                });
                };   
               
    writeFile(`data/scene/${$stage.scene.constructor.name}.json` , JSON.stringify(jsonnull'\t') );
            };
     
    #6
  7. Hisao Shou

    Hisao Shou Veteran Veteran

    Messages:
    87
    Likes Received:
    13
    Thank you guys! Your methods worked perfectly!
    Now it exports the folder from the desired location correctly
     
    #7

Share This Page