【问题标题】:Node JS copy only certain filesNode JS 只复制某些文件
【发布时间】:2017-03-05 23:15:21
【问题描述】:

我有一个这样的输入目录:

resouces
├── a.avi
├── b.mp3
├── c.pdf
├── d.png
└── ...

我正在尝试生成以下内容:

resouces
├── audio
    └── *.mp3
├── video
    └── *.avi
└── ...

我正在使用 fs-extra npm 模块。这是我的代码:

fse.ensureDir(resourcesOutputDirectory, (error) => {
    if (error) {
        console.err("An error ocurred creating the resources directory " + error.message);
    } else {
        fse.copy(resourcesInputDirectory, resourcesOutputDirectory, "/**/*.mp3", (err) => {
            if (err) {
                console.err("An error ocurred moving resource directory to XML exported directory " + err.message);
            } else {
                console.log("Files has been succesfully copied");
            }
         });
     }
});

我不知道如何正确使用过滤器选项(复制调用中的第三个参数)仅将某些文件复制到我的输出目录。

提前致谢!

【问题讨论】:

  • 阅读 fse 文档让我相信,虽然文档中的示例显然是错误的,但您应该放置一个函数,而不是 "/**/*.mp3",当您返回 true想要复制文件,如果不是,false。喜欢(file) => {return (file.endsWith('.mp3');}

标签: javascript node.js npm fs


【解决方案1】:

Looking at the docs 看起来好像您不能使用 glob(就像您在示例中所做的那样)。您可以使用返回布尔值的函数或正则表达式。

例如,如果你想匹配所有的 mp3 或 avis 那么你可以这样做;

fse.copy(inDir, outDir, /.*(.mp3|.avi)$/, (err) => { })

【讨论】:

  • 这是我的第一个方法。但它没有复制任何东西。 Y 尝试 {filter: {test: /.*(.mp3|.avi)$/}},正如文档所说:过滤器:函数或正则表达式来过滤复制的文件。如果是函数,则返回 true 以包含,false 以排除。如果是正则表达式,与函数相同,其中过滤器为 filter.test。但它没有工作:(
  • 这根本行不通。
【解决方案2】:

终于明白了:

正如@Jivings 所说,我只需要一个正则表达式作为过滤器。但是,问题是 fse 的复制方法使用 ncp,现在似乎有过滤器的错误。使用 copySync 有效。

【讨论】:

    【解决方案3】:

    使用此gist 选择性地从文件夹复制文件并提供特定的输出名称

    const fs = require('fs-extra');
    const folders = [
      {
        path: './build/static/css',
        regex: /^(main).[\w]*.css$/,
        outputFile: '../public-pages/style/sme.css'
      },
      {
        path: './build/static/js',
        regex: /^(main).[\w]*.js$/,
        outputFile: '../public-pages/js/sme.js'
      }
    ];
    /*
    following code will copy files from ./build/static/css matching the regex pattern to new location specified by output file
    */
    folders.forEach(folder => {
      fs.readdirSync(folder.path).forEach(file => {
        if (folder.regex.test(file)) {
          console.log(`copying file ${file}`);
          fs.copy(`${folder.path}/${file}`, folder.outputFile)
            .then(() => console.log('success!'))
            .catch(err => console.error(err));
        }
      });
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多