How to move things from a folder to another?

Is is possible to, using javascript, move all files from a folder to another? And what If I want to move specific named files, listed in a string, from one folder to another?

For example(String):
Let's say I've a string with "move folder1/foderinside1 folder1/folderdestiny file1.jpg file2.png file3.mp3" How do I get, and separate, all information after the folder1/folderdestiny as filenames(using Space to separate) and move them to the folderdestiny inside folder1 ?
And If I've "move folder1/foderinside1 folder1/folderdestiny all" it moves everything(including other folders inside folderinside1) that is in folderinside1 to folderdestiny?(I already know how to detect this "all" in the end, in this case I just would like to know how to automatically move everything)
(The string is going to be stored in a variable before being manipulate)


I tried searching on google, but I couldn't find something that would work with RM MV's version of NWJS
nop you need a bach code, .bat
try search on google
"how move file and folder with batch"

You maybe also can in js with a specific node module, but i don't know.
You can maybe create a .bat file and Execute it from nwJS commande, using Windows Shell.
https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
But I've seen in some places that nodeJS/NWJS is able to do it, I just couldn't find a code that work on MV(Or that I could make work)
But I've seen in some places that nodeJS/NWJS is able to do it, I just couldn't find a code that work on MV(Or that I could make work)
yes maybe.
you can create folder like this
PHP:
 if(!fs.existsSync(newFolderPath)){ fs.mkdirSync(newFolderPath)}; // create folder if not exsit
But for move , i don't know
Maybe try doing smaller tasks first and breaking down your idea into smaller parts.

What we want to do
  • Read a directory
  • Manipulate File(s)
  • Organize a string into a code ready format
  • Scan/Walk a directory recursively (loop through each directory and their files until we find what we want)
    • Determine type of item being scanned (file or directory)
    • Return an array of paths
To start, moving a file is easy, basically we don't actually move the file, we copy the contents of the file and write a new file. If we must remove all traces of the old files we can delete them with an package.

You will need to use two built in modules fs and path

Read a directory
Code:
const fs = require('fs')
fs.readdir('/path', options, callback)

Read a file
PHP:
const fs = require('fs')
fs.readFile('/path/file', 'utf8', callback);

Write a file
PHP:
fs.writeFile(file, data[, options], callback)

Check file type
PHP:
function fileType (path) {
  const item = fs.stat(path)
  return item.isDirectory() ? 'directory' : item.isFile() ? 'file' : null
}

With all the above we can move an entire directories contents, but first we need to make an easy to use function, re-usable and should be a higher order function

Scan/Walk a directory (Modified version of what I recently used - untested)
PHP:
/**
 * A lightweight directory walk, for traversing directories and its contents
 * entry point.
 * @param {string} input - The input path
 * @param {function} callback - The callback to run for each item
 */
function walkDirectory (input, callback = () => {}) {
  const type = fileType(input)
  try {
    switch (type) {
      case 'directory':
        fs.readdir(input, (paths) => {
          for (const path of paths) {
            walkDirectory(`${input}/${path}`)
          }
        })
        break
      case 'file':
        callback(input)
        break
    }
  } catch (error) {
    throw error
  }
}

The walkDirectory function will move through each directory and scan each file and run the callback function for each file and the callback will have the file path as it's argument.

PHP:
walkDirectory('./path/', (path) => {
  // Write file here, or perform other tasks first.
  try {
    fs.readFile(path, 'utf8', (data) => {
      fs.writeFile('path/to/move/files', data, 'utf8')
    })
  } catch (error) {
    throw error
  }
})

In theory all of this should work for you, I don't have time to test it at this moment but it follows the same logic of my already working code. If it don't work just let me know, or if you have question ask away. I hope most of it makes sense. You will most likely need to adjust some things to work for your specific scenario.

As for separating your string into something code readable, there are numerous ways to do this

If the string is only one path, use nodes path module to parse it

PHP:
path.parse('/home/user/dir/file.txt')
// Returns:
// {
// root : "/",
// dir : "/home/user/dir",
// base : "file.txt",
// ext : ".txt",
// name : "file"
// }

For your example above, I would just split the string into an array and then do a regex to check each element for an ext.

PHP:
const rawPaths = 'folder1/foderinside1 folder1/folderdestiny file1.jpg file2.png file3.mp3'
rawPaths.split(' ') // make into array using a space as a seperator

// Returns:
// ['folder1/foderinside1', 'folder1/folderdestiny', 'file1.jpg', 'file2.png', 'file3.mp3']

I'm not sure why you need to do this? Either way I hope with what I provided here you can come up with a solution of your own.
Maybe try doing smaller tasks first and breaking down your idea into smaller parts.

What we want to do
  • Read a directory
  • Manipulate File(s)
  • Organize a string into a code ready format
  • Scan/Walk a directory recursively (loop through each directory and their files until we find what we want)
    • Determine type of item being scanned (file or directory)
    • Return an array of paths
To start, moving a file is easy, basically we don't actually move the file, we copy the contents of the file and write a new file. If we must remove all traces of the old files we can delete them with an package.

You will need to use two built in modules fs and path

Read a directory
Code:
const fs = require('fs')
fs.readdir('/path', options, callback)

Read a file
PHP:
const fs = require('fs')
fs.readFile('/path/file', 'utf8', callback);

Write a file
PHP:
fs.writeFile(file, data[, options], callback)

Check file type
PHP:
function fileType (path) {
  const item = fs.stat(path)
  return item.isDirectory() ? 'directory' : item.isFile() ? 'file' : null
}

With all the above we can move an entire directories contents, but first we need to make an easy to use function, re-usable and should be a higher order function

Scan/Walk a directory (Modified version of what I recently used - untested)
PHP:
/**
 * A lightweight directory walk, for traversing directories and its contents
 * entry point.
 * @param {string} input - The input path
 * @param {function} callback - The callback to run for each item
 */
function walkDirectory (input, callback = () => {}) {
  const type = fileType(input)
  try {
    switch (type) {
      case 'directory':
        fs.readdir(input, (paths) => {
          for (const path of paths) {
            walkDirectory(`${input}/${path}`)
          }
        })
        break
      case 'file':
        callback(input)
        break
    }
  } catch (error) {
    throw error
  }
}

The walkDirectory function will move through each directory and scan each file and run the callback function for each file and the callback will have the file path as it's argument.

PHP:
walkDirectory('./path/', (path) => {
  // Write file here, or perform other tasks first.
  try {
    fs.readFile(path, 'utf8', (data) => {
      fs.writeFile('path/to/move/files', data, 'utf8')
    })
  } catch (error) {
    throw error
  }
})

In theory all of this should work for you, I don't have time to test it at this moment but it follows the same logic of my already working code. If it don't work just let me know, or if you have question ask away. I hope most of it makes sense. You will most likely need to adjust some things to work for your specific scenario.

As for separating your string into something code readable, there are numerous ways to do this

If the string is only one path, use nodes path module to parse it

PHP:
path.parse('/home/user/dir/file.txt')
// Returns:
// {
// root : "/",
// dir : "/home/user/dir",
// base : "file.txt",
// ext : ".txt",
// name : "file"
// }

For your example above, I would just split the string into an array and then do a regex to check each element for an ext.

PHP:
const rawPaths = 'folder1/foderinside1 folder1/folderdestiny file1.jpg file2.png file3.mp3'
rawPaths.split(' ') // make into array using a space as a seperator

// Returns:
// ['folder1/foderinside1', 'folder1/folderdestiny', 'file1.jpg', 'file2.png', 'file3.mp3']

I'm not sure why you need to do this? Either way I hope with what I provided here you can come up with a solution of your own.
Nice , hey thank for take time !
I would've been more detailed but my time is limited. I'm glad to help and I hope this helps everyone understand how to use fs to manipulate the file system. Any more questions feel free to ask and I'll do my best to answer.
I found this in the API documents, would 'fs.renameSync' work?

https://nodejs.org/docs/latest/api/fs.html#fs_fs_renamesync_oldpath_newpath
Maybe try doing smaller tasks first and breaking down your idea into smaller parts.

What we want to do
  • Read a directory
  • Manipulate File(s)
  • Organize a string into a code ready format
  • Scan/Walk a directory recursively (loop through each directory and their files until we find what we want)
    • Determine type of item being scanned (file or directory)
    • Return an array of paths
To start, moving a file is easy, basically we don't actually move the file, we copy the contents of the file and write a new file. If we must remove all traces of the old files we can delete them with an package.

You will need to use two built in modules fs and path

Read a directory
Code:
const fs = require('fs')
fs.readdir('/path', options, callback)

Read a file
PHP:
const fs = require('fs')
fs.readFile('/path/file', 'utf8', callback);

Write a file
PHP:
fs.writeFile(file, data[, options], callback)

Check file type
PHP:
function fileType (path) {
  const item = fs.stat(path)
  return item.isDirectory() ? 'directory' : item.isFile() ? 'file' : null
}

With all the above we can move an entire directories contents, but first we need to make an easy to use function, re-usable and should be a higher order function

Scan/Walk a directory (Modified version of what I recently used - untested)
PHP:
/**
 * A lightweight directory walk, for traversing directories and its contents
 * entry point.
 * @param {string} input - The input path
 * @param {function} callback - The callback to run for each item
 */
function walkDirectory (input, callback = () => {}) {
  const type = fileType(input)
  try {
    switch (type) {
      case 'directory':
        fs.readdir(input, (paths) => {
          for (const path of paths) {
            walkDirectory(`${input}/${path}`)
          }
        })
        break
      case 'file':
        callback(input)
        break
    }
  } catch (error) {
    throw error
  }
}

The walkDirectory function will move through each directory and scan each file and run the callback function for each file and the callback will have the file path as it's argument.

PHP:
walkDirectory('./path/', (path) => {
  // Write file here, or perform other tasks first.
  try {
    fs.readFile(path, 'utf8', (data) => {
      fs.writeFile('path/to/move/files', data, 'utf8')
    })
  } catch (error) {
    throw error
  }
})

In theory all of this should work for you, I don't have time to test it at this moment but it follows the same logic of my already working code. If it don't work just let me know, or if you have question ask away. I hope most of it makes sense. You will most likely need to adjust some things to work for your specific scenario.

As for separating your string into something code readable, there are numerous ways to do this

If the string is only one path, use nodes path module to parse it

PHP:
path.parse('/home/user/dir/file.txt')
// Returns:
// {
// root : "/",
// dir : "/home/user/dir",
// base : "file.txt",
// ext : ".txt",
// name : "file"
// }

For your example above, I would just split the string into an array and then do a regex to check each element for an ext.

PHP:
const rawPaths = 'folder1/foderinside1 folder1/folderdestiny file1.jpg file2.png file3.mp3'
rawPaths.split(' ') // make into array using a space as a seperator

// Returns:
// ['folder1/foderinside1', 'folder1/folderdestiny', 'file1.jpg', 'file2.png', 'file3.mp3']

I'm not sure why you need to do this? Either way I hope with what I provided here you can come up with a solution of your own.
I could understand some of it... But still I'm lost. Could you explain a bit more?

Btw1: The string is random(There can be 3 files written in the end, 1, or 50, for example), and as far as I could understand that code you showed in the end, it would only work if the string was exactly like that. Is there a way to read everything after the third part of the index of that string which I gave the example(After that /folder1/folderdestiny)?


Btw2: I'm trying to do something like a shell/cmd using nwjs(Of RPG MV) but a lot less powerful and more simple. Why? Because I'm weird :V . Also because I learn a lot more playing and creating random stuff than reading books, pdfs or what ever.


EDIT: I found a Way to copy file(s) using fs.createReadStream(example bellow, used to copy a .js file to plugins folder and include it in plugins.js list, ignore that last part for it's not useful here :V ), but it will only do to 1 file, just in local app folder(doesn't work when testing, only after export). Does someone know how to expand this to multiple files/folders?

Code:
var fs = require('fs');
fs.createReadStream('./'+$gameVariables.value(13).split(" ")[1]+'.js').pipe(fs.createWriteStream('./www/js/plugins/'+$gameVariables.value(13).split(" ")[1]+'.js'));
var data = fs.readFileSync('./www/js/plugins.js').toString().split("\n");
data.splice(5, 0, '{"name":"'+$gameVariables.value(13).split(" ")[1]+'","status":true,"description":"","parameters":{}},');
var text = data.join("\n");

fs.writeFile('./www/js/plugins.js', text, function (err) {
  if (err) return console.log(err);
});
fs.unlinkSync('./'+$gameVariables.value(13).split(" ")[1]+'.js')

And how to I get information (that I don't know the amount) from a string the way I said?(Spliting by space " ", then getting everything after folder1/folderdestiny, no matter how many things there are, and use each one as a file name. If there be just an "all", it moves everything inside the first written folder to the second)

Original thread: https://forums.rpgmakerweb.com/threads/how-to-move-things-from-a-folder-to-another.93559/