node.js에서 폴더를 재귀 적으로 복사


154

수동의 순서를하지 않고 폴더와 모든 콘텐츠를 복사 할 수있는 쉬운 방법이 있습니까 fs.readir, fs.readfile, fs.writefile재귀는?

이상적으로 이와 같이 작동하는 기능이 누락되어 있는지 궁금합니다.

fs.copy("/path/to/source/folder","/path/to/destination/folder");

3
모듈없이 이것을 할 수있는 방법이 있습니까? 아마도 재귀 함수 / 코드 조각입니까?
Sukima

@Sukima- 여기 내 답변을 참조 하십시오 .
jmort253

답변:


121

ncp 모듈을 사용할 수 있습니다 . 나는 이것이 당신이 필요로 생각합니다


2
완전한! npm install ncp30 대 미만에서 일하고 있습니다. 감사.
Aebsubis

1
렌치가 나에게 더 좋습니다. 더 많은 옵션을 지원합니다. 예를 들어 NCP를 사용하면 심볼릭 링크를 확인할 수 없습니다.
Slava Fomin II

3
놀라운 보너스로 크로스 플랫폼 npm 실행 스크립트에서 ncp를 사용할 수 있습니다.
Ciantic

fs-extra가 올바르게 수행되는 콜백에서 ncp가 발생하지 않는 간단한 경우가 있습니다.
bumpmann

40
ncp 는 유지되지 않은 것으로 나타납니다 . fs-extra 가 아마도 가장 좋은 옵션 일 것입니다.
chris

74

이것은 추가 모듈 없이이 문제를 해결하는 나의 접근 방식입니다. 내장 fspath모듈 만 사용하십시오 .

참고 : 이것은 fs의 읽기 / 쓰기 기능을 사용하므로 메타 데이터 (생성 시간 등)를 복사하지 않습니다. 노드 8.5부터는 copyFileSyncOS 복사 기능을 호출하여 메타 데이터를 복사 하는 기능이 있습니다. 아직 테스트하지는 않았지만 교체하는 것이 좋습니다. ( https://nodejs.org/api/fs.html#fs_fs_copyfilesync_src_dest_flags 참조 )

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

function copyFileSync( source, target ) {

    var targetFile = target;

    //if target is a directory a new file with the same name will be created
    if ( fs.existsSync( target ) ) {
        if ( fs.lstatSync( target ).isDirectory() ) {
            targetFile = path.join( target, path.basename( source ) );
        }
    }

    fs.writeFileSync(targetFile, fs.readFileSync(source));
}

function copyFolderRecursiveSync( source, target ) {
    var files = [];

    //check if folder needs to be created or integrated
    var targetFolder = path.join( target, path.basename( source ) );
    if ( !fs.existsSync( targetFolder ) ) {
        fs.mkdirSync( targetFolder );
    }

    //copy
    if ( fs.lstatSync( source ).isDirectory() ) {
        files = fs.readdirSync( source );
        files.forEach( function ( file ) {
            var curSource = path.join( source, file );
            if ( fs.lstatSync( curSource ).isDirectory() ) {
                copyFolderRecursiveSync( curSource, targetFolder );
            } else {
                copyFileSync( curSource, targetFolder );
            }
        } );
    }
}

이름에 공백이 있으면 폴더를 복사하지 않습니다.
31415926

나를 위해 이름에 공백이있는 폴더를 복사합니다. @victor 의해 수정 된 오류로 인해 발생한 것일 수 있습니다. 이 기능을 꽤 규칙적으로 사용하고 있기 때문에 (현재 상태에서, 동일한 수정 빅터가 업데이트 한 것을 잊어 버렸으므로) 일반적으로 작동한다고 확신합니다.
Simon Zyx

1
또한 필요 : javascript var fs = require('fs'); var path = require('path');
Tyler

2
실제로 파일을 복사하지는 않습니다. 그것들을 읽고 씁니다. 복사하지 않습니다. 복사에는 생성 날짜와 Windows 및 MacOS 모두에서 지원하며이 코드에 의해 복사되지 않은 다른 메타 데이터 스트림이 포함됩니다. 노드 8.5부터 fs.copy또는 fs.copySyncMacOS 및 Windows에서 OS 레벨 복사 기능을 호출 하거나 실제로 호출 할 때 실제로 파일을 복사해야합니다.
gman

1
죄송합니다 fs.copyFile. Mac과 Windows에서 노드 소스를 파헤
치면

52

내용과 함께 폴더 복사를 지원하는 일부 모듈이 있습니다. 가장 인기있는 것은 렌치입니다

// Deep-copy an existing directory
wrench.copyDirSyncRecursive('directory_to_copy', 'location_where_copy_should_end_up');

대안은 node-fs-extra입니다.

fs.copy('/tmp/mydir', '/tmp/mynewdir', function (err) {
  if (err) {
    console.error(err);
  } else {
    console.log("success!");
  }
}); //copies directory, even if it has subdirectories or files

3
복사 할 디렉토리에 기호 링크가 포함 된 경우 렌치가 실패합니다
DoubleMalt

2
디렉토리가 이미 존재하면 Windows에서도 실패합니다. ncp 는 즉시 사용됩니다.
담임

6
node-fs-extra가 나를 위해 일했습니다. 원래 fs를 상속 받았으며 프로세스 처리 방법이 마음에 들었습니다. 앱에서 업데이트 할 코드가 적습니다.
dvdmn

15
그이 유의하시기 바랍니다 wrench사용되지 않으며 교체해야합니다 node-fs-extra( github.com/jprichardson/node-fs-extra가 )
Ambidex

1
렌치는 실제로 파일을 복사하지 않습니다. 그것들을 읽고 쓴 다음 날짜를 복사합니다. 복사하지 않습니다. 복사에는 Windows와 MacOS 모두에서 지원하며 렌치로 복사하지 않는 다른 메타 데이터 스트림이 포함됩니다.
gman

38

디렉토리를 재귀 적으로 복사하는 함수는 다음과 같습니다.

const fs = require("fs")
const path = require("path")

/**
 * Look ma, it's cp -R.
 * @param {string} src The path to the thing to copy.
 * @param {string} dest The path to the new copy.
 */
var copyRecursiveSync = function(src, dest) {
  var exists = fs.existsSync(src);
  var stats = exists && fs.statSync(src);
  var isDirectory = exists && stats.isDirectory();
  if (isDirectory) {
    fs.mkdirSync(dest);
    fs.readdirSync(src).forEach(function(childItemName) {
      copyRecursiveSync(path.join(src, childItemName),
                        path.join(dest, childItemName));
    });
  } else {
    fs.copyFileSync(src, dest);
  }
};

3
실제 복사 기능을 삽입하더라도 기호 링크를 따르지 않아야합니다 ( fs.lstatSync대신 사용 fs.statSync)
Simon Zyx

3
이 혼동의 원인은 fs.unlink가 파일을 삭제하지만 fs.link는 복사가 아니라 링크라는 것입니다.
Simon Zyx

3
@SimonSeyock : 맞습니다. IT가 linking복사하지 않습니다. 문제는 연결된 파일의 내용을 수정할 때 원본 파일도 변경됩니다.
Abdennour TOUMI


22

Linux / unix OS의 경우 쉘 구문을 사용할 수 있습니다

const shell = require('child_process').execSync ; 

const src= `/path/src`;
const dist= `/path/dist`;

shell(`mkdir -p ${dist}`);
shell(`cp -r ${src}/* ${dist}`);

그게 다야!


1
천만에요
Abdennour TOUMI

1
이것이 가장 간단한 해결책입니다. UNIX 도구를 다시 발명 할 필요가 없습니다!
Michael Franzl

11
nodejs가 OSX / linux / windows에서 실행되기 때문에 이것은 모두 3이 아니라 2에 대한 답입니다.
mjwrazor

2
@AbdennourTOUMI Windows 서버에서 실행중인 경우 어떻게해야합니까?
mjwrazor 2016 년

3
그렇기 때문에 "리눅스 / 유닉스 OS의 경우 쉘 구문을 사용할 수 있습니다."라는 대답을 시작했습니다. 👍🏼
Abdennour TOUMI

19

fs-extra 모듈은 매력처럼 작동합니다.

fs-extra 설치

$ npm install fs-extra

다음은 소스 디렉토리를 대상 디렉토리에 복사하는 프로그램입니다.

// include fs-extra package
var fs = require("fs-extra");

var source = 'folderA'
var destination = 'folderB'

// copy source folder to destination
fs.copy(source, destination, function (err) {
    if (err){
        console.log('An error occured while copying the folder.')
        return console.error(err)
    }
    console.log('Copy completed!')
});

참고 문헌

fs-extra : https://www.npmjs.com/package/fs-extra

예 : NodeJS 튜토리얼 - 폴더 Node.js를 복사


이 프로세스가 디렉토리를 바꾸거나 병합합니까?
SM Shahinul 이슬람

14

이것이 내가 개인적으로하는 방법입니다.

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));
        }
    });
}

폴더 및 파일에 사용


3
이 솔루션은 간결하고 간단합니다. 이것은 내가하는 일과 거의 똑같을 것이므로 +1입니다. 코드의 주석으로 답을 개선하고이 솔루션이 다른 솔루션보다 선호되는 이유와 그 단점을 설명해야합니다. -필요한 모듈도 업데이트하십시오. ( "path", "fs")
Andrew

폴더가 맨 위에 있는지 확인하십시오. 생명을 구합니다 ;-) if (! fs.existsSync (to)) fs.mkdirSync (to);
Tobias

9

몇 단계 만 거치면 소스 폴더를 다른 대상 폴더로 복사하는 작은 실제 예제를 만들었습니다 (ncp를 사용한 @ shift66 응답 기반).

1 단계-ncp 모듈 설치 :

npm install ncp --save

2 단계-copy.js 작성 (srcPath 및 destPath 변수를 필요한대로 수정) :

var path = require('path');
var ncp = require('ncp').ncp;

ncp.limit = 16;

var srcPath = path.dirname(require.main.filename); //current folder
var destPath = '/path/to/destination/folder'; //Any destination folder

console.log('Copying files...');
ncp(srcPath, destPath, function (err) {
  if (err) {
    return console.error(err);
  }
  console.log('Copying files complete.');
});

3 단계-실행

node copy.js

7

이것은 노드 10에서 매우 쉽습니다.

const FSP = require('fs').promises;

async function copyDir(src,dest) {
    const entries = await FSP.readdir(src,{withFileTypes:true});
    await FSP.mkdir(dest);
    for(let entry of entries) {
        const srcPath = Path.join(src,entry.name);
        const destPath = Path.join(dest,entry.name);
        if(entry.isDirectory()) {
            await copyDir(srcPath,destPath);
        } else {
            await FSP.copyFile(srcPath,destPath);
        }
    }
}

dest존재하지 않는 것으로 가정 합니다.


3
우리는이를 사용하여 노드 8.x에서 작업을 얻을 수 require('util').promisifyfs.mkdir하고 fs.copyFile대신 require('fs').promisesv11.1에서 아직 실험이다.
Sơn Trần-Nguyễn

@sntran 8.x에 withFileTypes옵션이 있습니까? 그것은 당신에게 stat전화 를 절약하기 때문에
mpen

불행히도 8.x에는 withFileTypes옵션 이 없습니다 .
Sơn Trần-Nguyễn

@ SơnTrần - 응웬 8.x의 도달 년 12 월 31 일 2019 삶의 끝 - 업그레이드하는 시간 :-) 수 있습니다
mpen

6

나는 이미 많은 답변을 알고 있지만 아무도 간단한 방법으로 대답하지 않았습니다. fs-exra 공식 문서 와 관련 하여 매우 쉽게 할 수 있습니다.

const fs = require('fs-extra')

// copy file
fs.copySync('/tmp/myfile', '/tmp/mynewfile')

// copy directory, even if it has subdirectories or files
fs.copySync('/tmp/mydir', '/tmp/mynewdir')

재귀 옵션을 설정하십시오. fs.copySync ( '/ tmp / mydir', '/ tmp / mynewdir', {재귀 : true})
Dheeraj Kumar

언급 한 github doc{ recursive: true } 에서 옵션 을 찾을 수 없습니다 . 작동하는지 모르겠습니다.
프레디 다니엘

우리는 fs-extra에 대해 이야기하고 있지만 github 링크는 node-fs-extra를 가리 킵니다. 다른 도서관이 될 수 있습니까?
Dheeraj Kumar

@DheerajKumar, 그것은 github에서 node-fs-extra를 보여주고 npm 에서는 fs-extra를 보여줍니다 . 둘 다 같은지 모르겠습니다. npm
Freddy Daniel

fs-extra가 fs를 대체합니까?
매트

4

간단한 노드 스크립트를 작성하고 있기 때문에 스크립트 사용자가 많은 외부 모듈과 종속성을 가져 오기를 원하지 않기 때문에 사고 뚜껑을 쓰고 bash에서 명령 실행을 검색했습니다. 껍질.

이 node.js 코드 스 니펫은 node-webkit.app라는 폴더를 build라는 폴더에 반복적으로 복사합니다.

   child = exec("cp -r node-webkit.app build", function(error, stdout, stderr) {
        sys.print("stdout: " + stdout);
        sys.print("stderr: " + stderr);
        if(error !== null) {
            console.log("exec error: " + error);
        } else {

        }
    });

dzone의 Lance Pollard 에게 감사의 말을 전 합니다.

위의 스 니펫은 Mac OS 및 Linux와 같은 Unix 기반 플랫폼으로 제한되지만 Windows에서도 유사한 기술이 작동 할 수 있습니다.


4

@ mallikarjun-m 감사합니다!

fs-extra 는 그 일을했으며 콜백을 제공하지 않으면 약속을 반환 할 수도 있습니다 ! :)

const path = require('path')
const fs = require('fs-extra')

let source = path.resolve( __dirname, 'folderA')
let destination = path.resolve( __dirname, 'folderB')

fs.copy(source, destination)
  .then(() => console.log('Copy completed!'))
  .catch( err => {
    console.log('An error occured while copying the folder.')
    return console.error(err)
  })

2

디렉토리가 존재하면 심볼릭 링크 지원 +를 가진 것은 던지지 않습니다.

function copyFolderSync(from, to) {
  try {
    fs.mkdirSync(to);
  } catch(e) {}

  fs.readdirSync(from).forEach((element) => {
    const stat = fs.lstatSync(path.join(from, element));
    if (stat.isFile()) {
      fs.copyFileSync(path.join(from, element), path.join(to, element));
    } else if (stat.isSymbolicLink()) {
      fs.symlinkSync(fs.readlinkSync(path.join(from, element)), path.join(to, element));
    } else if (stat.isDirectory()) {
      copyFolderSync(path.join(from, element), path.join(to, element));
    }
  });
}

1

이 코드는 모든 폴더를 모든 위치에 재귀 적으로 복사하여 정상적으로 작동합니다. Windows 만 해당

var child=require("child_process");
function copySync(from,to){
    from=from.replace(/\//gim,"\\");
    to=to.replace(/\//gim,"\\");
    child.exec("xcopy /y /q \""+from+"\\*\" \""+to+"\\\"");
}

새로운 플레이어를 만들기 위해 내 텍스트 기반 게임에 완벽하게 작동합니다.


1

fs-extra 및 copy-dir을 복사 폴더로 재귀 적으로 시도했습니다. 그러나 나는 그것을 원한다

  1. 정상적으로 작동합니다 (copy-dir에서 부적합한 오류가 발생 함)
  2. 필터에서 filepath와 filetype의 두 가지 인수를 제공합니다 (fs-extra가 파일 형식을 알려주지 않음)
  3. dir-to-subdir 점검 및 dir-to-file 점검

그래서 나는 내 자신을 썼다.

//node module for node 8.6+
var path=require("path");
var fs=require("fs");

function copyDirSync(src,dest,options){
  var srcPath=path.resolve(src);
  var destPath=path.resolve(dest);
  if(path.relative(srcPath,destPath).charAt(0)!=".")
    throw new Error("dest path must be out of src path");
  var settings=Object.assign(Object.create(copyDirSync.options),options);
  copyDirSync0(srcPath,destPath,settings);
  function copyDirSync0(srcPath,destPath,settings){
    var files=fs.readdirSync(srcPath);
    if (!fs.existsSync(destPath)) {
      fs.mkdirSync(destPath);
    }else if(!fs.lstatSync(destPath).isDirectory()){
      if(settings.overwrite)
        throw new Error(`Cannot overwrite non-directory '${destPath}' with directory '${srcPath}'.`);
      return;
    }
    files.forEach(function(filename){
      var childSrcPath=path.join(srcPath,filename);
      var childDestPath=path.join(destPath,filename);
      var type=fs.lstatSync(childSrcPath).isDirectory()?"directory":"file";
      if(!settings.filter(childSrcPath,type))
        return;
      if (type=="directory") {
        copyDirSync0(childSrcPath,childDestPath,settings);
      } else {
        fs.copyFileSync(childSrcPath, childDestPath, settings.overwrite?0:fs.constants.COPYFILE_EXCL);
        if(!settings.preserveFileDate)
          fs.futimesSync(childDestPath,Date.now(),Date.now());
      }
    });
  }
}
copyDirSync.options={
  overwrite: true,
  preserveFileDate: true,
  filter: function(filepath,type){return true;}
};

mkdirp의 대안 인 유사한 함수 mkdirs

function mkdirsSync(dest) {
  var destPath=path.resolve(dest);
  mkdirsSync0(destPath);
  function mkdirsSync0(destPath){
    var parentPath=path.dirname(destPath);
    if(parentPath==destPath)
      throw new Error(`cannot mkdir ${destPath}, invalid root`);
    if (!fs.existsSync(destPath)) {
      mkdirsSync0(parentPath);
      fs.mkdirSync(destPath);
    }else if(!fs.lstatSync(destPath).isDirectory()){
      throw new Error(`cannot mkdir ${destPath}, a file already exists there`);
    }
  }
}

0

디렉토리간에 파일을 재귀 적으로 복사 (copyFileSync)하거나 이동 (renameSync)하기 위해이 기능을 작성했습니다.

//copy files
copyDirectoryRecursiveSync(sourceDir, targetDir);
//move files
copyDirectoryRecursiveSync(sourceDir, targetDir, true);


function copyDirectoryRecursiveSync(source, target, move) {
if (!fs.lstatSync(source).isDirectory()) return;

var operation = move ? fs.renameSync : fs.copyFileSync;
fs.readdirSync(source).forEach(function (itemName) {
    var sourcePath = path.join(source, itemName);
    var targetPath = path.join(target, itemName);

    if (fs.lstatSync(sourcePath).isDirectory()) {
        fs.mkdirSync(targetPath);
        copyDirectoryRecursiveSync(sourcePath, targetDir);
    }
    else {
        operation(sourcePath, targetPath);
    }
});}

0

Linux에 있고 성능에 문제가없는 경우 모듈 의 exec함수를 사용하여 child_processbash 명령을 실행할 수 있습니다 .

const { exec } = require('child_process');
exec('cp -r source dest', (error, stdout, stderr) => {...});

경우에 따라 전체 모듈을 다운로드하거나 fs모듈을 사용하는 것보다이 솔루션이 더 깨끗하다는 것을 알았습니다 .


0

ncp 는 파일 설명자를 잠그고 아직 잠금이 해제되지 않은 경우 콜백을 시작합니다. 대신 재귀 복사 모듈 을 사용하는 것이 좋습니다 . 이벤트를 지원하며 복사 종료를 확신 할 수 있습니다.


0

패키지를 선택할 때주의하십시오. copy-dir과 같은 일부 패키지는 0x1fffffe8자를 초과하는 큰 파일 복사를 지원하지 않습니다. 다음과 같은 오류가 발생합니다.

buffer.js:630 Uncaught Error: Cannot create a string longer than 0x1fffffe8 characters 

내 프로젝트 중 하나에서 이와 같은 것을 경험했습니다. 궁극적으로 사용하고 있던 패키지를 변경하고 많은 코드를 조정해야했습니다. 나는 이것이 매우 즐거운 경험이 아니라고 말할 것입니다.

여러 원본과 여러 대상 복사본이 필요한 경우 더 나은 복사를 사용하여 다음과 같이 쓸 수 있습니다 .

// copy from multiple source into a directory
bCopy(['/path/to/your/folder1', '/path/to/some/file.txt'], '/path/to/destination/folder');

또는 :

// copy from multiple source into multiple destination
bCopy(['/path/to/your/folder1', '/path/to/some/file.txt'], ['/path/to/destination/folder', '/path/to/another/folder']);

-1

YES, ncp입니다 cool하지만 ...

당신은 그것의 기능을 만드는 것을 약속하거나 약속해야 할 것입니다 super cool. 사용 중이므로 tools파일에 추가 하여 재사용하십시오.

아래는 작업 버전 Async및 용도 Promises.


index.js

const {copyFolder} = require('./tools/');

return copyFolder(
    yourSourcePath,
    yourDestinationPath
)
.then(() => {
    console.log('-> Backup completed.')
}) .catch((err) => {
    console.log("-> [ERR] Could not copy the folder: ", err);
})

tools.js

const ncp = require("ncp");

/**
 * Promise Version of ncp.ncp()
 * 
 * This function promisifies ncp.ncp().
 * We take the asynchronous function ncp.ncp() with 
 * callback semantics and derive from it a new function with
 * promise semantics.
 */
ncp.ncpAsync = function (sourcePath, destinationPath) {
  return new Promise(function (resolve, reject) {
      try {
          ncp.ncp(sourcePath, destinationPath, function(err){
              if (err) reject(err); else resolve();
          });
      } catch (err) {
          reject(err);
      }
  });
};

/**
 * Utility function to copy folders asynchronously using
 * the Promise returned by ncp.ncp(). 
 */
const copyFolder = (sourcePath, destinationPath) => {
    return ncp.ncpAsync(sourcePath, destinationPath, function (err) {
        if (err) {
            return console.error(err);
        }
    });
}
module.exports.copyFolder = copyFolder;

-1

이 문제에 대한 가장 쉬운 방법은 'fs'및 'Path'모듈과 일부 논리 만 사용하는 것입니다.

버전 번호를 설정하려면 루트 폴더의 모든 파일이 새 이름으로 복사됩니다. 이름'"

파일 이름 접두사 V 내용에 파일 이름이 추가되었습니다.

var fs = require('fs-extra');
var path = require('path');

var c = 0;
var i =0 ;
var v = "1.0.2";
var copyCounter = 0;
var directoryCounter = 0; 
var directoryMakerCounter = 0;
var recursionCounter = -1;
var Flag = false;
var directoryPath = [] ;
var directoryName = [] ;
var directoryFileName = [];
var fileName;
var directoryNameStorer;
var dc = 0;
var route ;



if (!fs.existsSync(v)){
   fs.mkdirSync(v);
}

var basePath = path.join(__dirname, v);


function walk(dir){

  fs.readdir(dir, function(err, items) {

    items.forEach(function(file){

        file = path.resolve(dir, file);

        fs.stat(file, function(err, stat){
            if(stat && stat.isDirectory()){

                directoryNameStorer = path.basename(file);
                route = file;
                route = route.replace("gd",v);

                directoryFileName[directoryCounter] = route;
                directoryPath[directoryCounter] = file;
                directoryName[directoryCounter] = directoryNameStorer;

                directoryCounter++;
                dc++;

                if (!fs.existsSync(basePath+"/"+directoryName[directoryMakerCounter])){
                    fs.mkdirSync(directoryFileName[directoryMakerCounter]);
                    directoryMakerCounter++;
                }

            }else{

                    fileName = path.basename(file);
                    if(recursionCounter >= 0){
                        fs.copyFileSync(file, directoryFileName[recursionCounter]+"/"+v+"_"+fileName, err => {
                            if(err) return console.error(err);
                        });
                        copyCounter++;
                    }else{
                        fs.copyFileSync(file, v+"/"+v+"_"+fileName, err => {
                            if(err) return console.error(err);
                        });
                        copyCounter++;    
                    }

                }
                if(copyCounter + dc == items.length && directoryCounter > 0 && recursionCounter < directoryMakerCounter-1){
                    console.log("COPY COUNTER :             "+copyCounter);
                    console.log("DC COUNTER :               "+dc);                        
                    recursionCounter++;
                    dc = 0;
                    copyCounter = 0;
                    console.log("ITEM DOT LENGTH :          "+items.length);
                    console.log("RECURSION COUNTER :        "+recursionCounter);
                    console.log("DIRECOTRY MAKER COUNTER :  "+directoryMakerCounter);
                    console.log(": START RECURSION :        "+directoryPath[recursionCounter]);
                    walk(directoryPath[recursionCounter]); //recursive call to copy sub-folder

                }

        })
    })
 });

}
 walk('./gd', function(err, data){ //Just Pass The Root Directory Which You Want to Copy
 if(err) throw err;
 console.log("done");
})

-1

이것이 내가 한 방법입니다.

let fs = require('fs');
let path = require('path');

그때:

let filePath = //your FilePath

let fileList = []
        var walkSync = function(filePath, filelist) 
        {
          let files = fs.readdirSync(filePath);
          filelist = filelist || [];
          files.forEach(function(file) 
          {
            if (fs.statSync(path.join(filePath, file)).isDirectory()) 
            {
              filelist = walkSync(path.join(filePath, file), filelist);
            }
            else 
            {
              filelist.push(path.join(filePath, file));
            }
          });

          // Ignore hidden files
          filelist = filelist.filter(item => !(/(^|\/)\.[^\/\.]/g).test(item));

          return filelist;
        };

그런 다음 메소드를 호출하십시오.

This.walkSync(filePath, fileList)
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.