Copy folder recursively in Node.js

前端 未结 25 1944
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 07:44

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

25条回答
  •  情深已故
    2020-12-04 08:11

    It looks like ncp and wrench both are no longer maintained. Probably the best option is to use fs-extra

    The Developer of Wrench directs users to use fs-extra as he has deprecated his library

    copySync & moveSync both will copy and move folders even if they have files or subfolders and you can easily move or copy files using it

    const fse = require('fs-extra');
    
    const srcDir = `path/to/file`;
    const destDir = `path/to/destination/directory`;
    
    // To copy a folder or file
    fse.copySync(srcDir, destDir, function (err) {
      if (err) {
        console.error(err);
      } else {
        console.log("success!");
      }
    });
    

    OR

    // To move a folder or file 
    fse.moveSync(srcDir, destDir, function (err) {
      if (err) {
        console.error(err);
      } else {
        console.log("success!");
      }
    });
    

提交回复
热议问题