Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
75 views
in Technique[技术] by (71.8m points)

javascript - Cant copy files to unknown Directory in Node.js

const { resolve } = require("path");
const prompt = require('prompt');
const fsPath = require('fs-path');

// Get files from Dir
const getFiles = dir => {
  const stack = [resolve(dir)];
  const files = [];
  while (stack.length) {
    dir = stack.pop();
    fs.readdirSync(dir).forEach(item => {
      const path = resolve(dir, item);
      (fs.statSync(path).isDirectory() ? stack : files).push(path);
    });
  }
  return files;
};

prompt.start();

// Prompt for Dir
prompt.get(['from', 'to'], async(err, res) => {
    if (err) {
        return console.log(err);
    } else {
        let fromFiles = await getFiles(String(res.from));
        let toFiles = await getFiles(String(res.to));
        let isEqual = JSON.stringify(fromFiles) == JSON.stringify(toFiles);
        let out = res.to;
        
        if (isEqual) {
            return console.log('Both folders are same. Try it with an other folder!');
        } else {
            let dif = [];
            // Check differences -> to path
            await fromFiles.forEach(path => {
                if (!toFiles.includes(path)) {
                    dif.push(path)
                }
            });

            dif.forEach(difference => {
                fsPath.copy(`${difference}`, `${out + difference.split(__dirname)[1]}`, (error) => {
                    if (error) {
                        console.log(error);
                    } else  {
                        console.log('Successfully copied item.')
                    }
                });
            });
        }
    }
});

Hi Guys, in the code above i want to only copy files that dont exist in the 'toFiles' Folder. But I have a problem, if I try to do it with the fsPath npm Package it gives out errors like this 'Error: ENOENT: no such file or directory'. Normally the package should create the parent folders if there are none. But it somehow doesnt work. Could anybody look after the code and try to fix it? Thanks very much.

question from:https://stackoverflow.com/questions/65542108/cant-copy-files-to-unknown-directory-in-node-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The folder doesn't exist, you can create the folder first with mkdir:

fsPath.mkdir(String(res.to), { recursive: true }, (err) => {
  if (err) throw err;
  // code
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...