Javascript 在 node.js 中递归复制文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13786160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:54:01  来源:igfitidea点击:

Copy folder recursively in node.js

javascriptnode.js

提问by lostsource

Is there an easier way to copy a folder and all its content without manually doing a sequence of fs.readir, fs.readfile, fs.writefilerecursively ?

有没有更简单的方法来复制文件夹及其所有内容,而无需手动执行fs.readir, fs.readfilefs.writefile递归的序列?

Just wondering if i'm missing a function which would ideally work like this

只是想知道我是否缺少一个可以像这样理想地工作的函数

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

采纳答案by shift66

You can use ncpmodule. I think this is what you need

您可以使用ncp模块。我认为这就是你所需要的

回答by Simon Zyx

This is my approach to solve this problem without any extra modules. Just using the built-in fsand pathmodules.

这是我在没有任何额外模块的情况下解决这个问题的方法。只需使用内置fspath模块。

Note:This does use the read / write functions of fs so it does not copy any meta data (time of creation etc.). As of node 8.5 there is a copyFileSyncfunctions available which call the OS copy functions and therefore also copies meta data. I did not test them yet, but it should work to just replace them. (See https://nodejs.org/api/fs.html#fs_fs_copyfilesync_src_dest_flags)

注意:这确实使用了 fs 的读/写功能,因此它不会复制任何元数据(创建时间等)。从节点 8.5 开始,有一个copyFileSync函数可以调用 OS 复制函数,因此也可以复制元数据。我还没有测试它们,但应该可以更换它们。(见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 );
            }
        } );
    }
}

回答by zemirco

There are some modules that support copying folders with their content. The most popular would be wrench

有一些模块支持复制文件夹及其内容。最受欢迎的是扳手

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

An alternative would be node-fs-extra

另一种选择是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

回答by Lindsey Simon

/**
 * 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.copyFile(src, dest);    // UPDATE FROM:    fs.linkSync(src, dest);
  }
};

回答by Will

fs-extraworked for me when ncpand wrenchfell short:

fs-extra为我工作的时候ncpwrench没有达到:

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

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

回答by Abdennour TOUMI

For linux/unix OS, you can use the shell syntax

对于 linux/unix 操作系统,您可以使用 shell 语法

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

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

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

That's it!

就是这样!

回答by Mallikarjun M

fs-extra module works like a charm.

fs-extra 模块就像一个魅力。

Install fs-extra

安装 fs-extra

$ npm install fs-extra

Following is the program to copy source directory to destination directory.

以下是将源目录复制到目标目录的程序。

// 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!')
});

References

参考

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

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

Example : NodeJS Tutorial- Node.js Copy a Folder

示例:NodeJS 教程- Node.js 复制文件夹

回答by Mallikarjun M

This is how I would do it personally:

这就是我个人的做法:

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

works for folders and files

适用于文件夹和文件

回答by Shahar

I created a small working example that copies a source folder to another destination folder in just a few steps (based on @shift66 answer using ncp):

我创建了一个小的工作示例,只需几步即可将源文件夹复制到另一个目标文件夹(基于使用 ncp 的 @shift66 答案):

step 1 - Install ncp module:

第 1 步 - 安装 ncp 模块:

npm install ncp --save

step 2 - create copy.js (modify srcPath and destPath vars to whatever you need):

第 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.');
});

step 3 - run

第 3 步 - 运行

node copy.js

回答by Freddy Daniel

I know so many answers already here but no one answered it simple way. Regarding fs-exra official documentation, you can do it very easy

我知道这里已经有很多答案,但没有人以简单的方式回答。关于 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')