NodeJS,批处理文件,替代每个文件写入过多 objects/functions?

NodeJS, batch processing files, alternative to writing excessive objects/functions per file?

我需要获取所有名为 templates/ 的小胡子模板目录,并使用 hogan 编译它们。

理论上,假设他们的名字是,

file1.mustache file2.mustache file3.mustache

然后我们查看每个视图,并将结果保存到名为 build/ 的输出目录中。

理论上,生成的名称将是,

name.file1 名称.file2 名称.file3

显然异步更可取,但我最感兴趣的是您如何有效地做到这一点?我无法相信唯一的方法是对每个文件对象和匿名函数进行操作。

您可以结合使用 fs-promise 模块和 Promise.all 来轻松地并行读取、处理和写入文件:

const fsp = require('fs-promise');

function processTemplate(filename) {
  return fsp.readFile(filename, 'utf8')
    .then((template) => hogan.compile(template))
    .then((compiledTemplate) => fsp.writeFile('path/to/compiled', compiledTemplate));
}

fsp.readdir('./templates')
  .then((files) => Promise.all(files.map(processTemplate)))
  .catch((error) => console.log(error));

虽然我不确定我理解你所说的 "per file objects and anonymous functions" 的意思。