NodeJS won't copy folder to another folder

Hisao Shou

Veteran
Veteran
Joined
Jan 8, 2015
Messages
133
Reaction score
16
Primarily Uses
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?
 

peq42_

Yeet
Veteran
Joined
Feb 5, 2016
Messages
480
Reaction score
285
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
 

Adventurer_inc.

Technically a Programmer
Veteran
Joined
Sep 12, 2015
Messages
99
Reaction score
40
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
 

Hisao Shou

Veteran
Veteran
Joined
Jan 8, 2015
Messages
133
Reaction score
16
Primarily Uses
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
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.
 

peq42_

Yeet
Veteran
Joined
Feb 5, 2016
Messages
480
Reaction score
285
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.
})
 

Jonforum

Veteran
Veteran
Joined
Mar 28, 2016
Messages
1,615
Reaction score
1,417
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(path, content, '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(json, null, '\t') );
        };
 

Hisao Shou

Veteran
Veteran
Joined
Jan 8, 2015
Messages
133
Reaction score
16
Primarily Uses
Thank you guys! Your methods worked perfectly!
Now it exports the folder from the desired location correctly
 

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

Latest Threads

Latest Posts

Latest Profile Posts

If you had some musical requests in line with me.. feel free to re post! Corona has killed me and have recently got my internet back <3
I'm now working on procedural generated World Maps for my own project.
Is there anyone who's interested in having this Plugin for his own game?
I have a dream where RMer are not blinded and too dependant on published script / plugins...
RM MV ACE? 2020? Super? Legends? Sword and Shield? 2.5D? RM Pixel? RM 2: Revenge of Squared RTP tiles? Don't mind me, I'm just wondering about what will be the name of the next engine.


So I came up with a new look for the paths, and along the way realized health bars are so overrated, so now a crazy red light trail follows her and gets shorter as her life decreases. :LZSexcite:

Forum statistics

Threads
98,211
Messages
950,358
Members
129,506
Latest member
TakuPlayz
Top