试图找到一种方法来读取目录中的所有文件,以编程方式重新创建和写入文件

时间:2019-05-29 23:12:45

标签: node.js templates gulp

我正在尝试使用内置于文件结构模块/包中的节点来尝试读写文件。我正在寻找一种方法来读取特定目录中的所有文件,重新创建文件并进行任何更改。

基本上,如果我有一个名为templates/_template-1.html的文件,它将重新创建到另一个名为pages/template-1.html的目录中。不必在gulpfile.js中手动声明每个文件。以下代码当前正在开发中。

基本上,它会打印tpl个已写入的文件,然后将它们重新写成基本的html。

/*------------------ INDEX -------------------*/
/* Build index file for the final HTML form
 */
gulp.task("build:index", function() {
    let templateFiles = glob.sync("templates/**/*.tpl"),
        templates = {},

        RESPONSIVE_HTML = fs.readFileSync("_responsive.html", "utf8"),
        THE_HTML = fs.readFileSync("_design-system.html", "utf8"),
        THE_VISUAL_LIBRARY = fs.readFileSync("_visual-library.html", "utf8");

    // Discover all templates
    for (let file in templateFiles) {
        file = templateFiles[file];

        let template = /templates\/(.+?)\.tpl/gi.exec(file)[1],
            text = fs.readFileSync(file, "utf8");

        template = path.basename(file, '.tpl');
        templates[template] = text;
    }

    // --------------------------------------------------------
    // Visible templates:
    _.each(templates, (partial, name) => {
        interpolateTemplate(partial, name, templates);
    });

    // replace the main HTML file
    for (let template in templates) {
        RESPONSIVE_HTML = RESPONSIVE_HTML.replace(new RegExp(`{[@$]${template}}`, "g"), templates[template]);
        THE_HTML = THE_HTML.replace(new RegExp(`{[@$]${template}}`, "g"), templates[template]);
        THE_VISUAL_LIBRARY = THE_VISUAL_LIBRARY.replace(new RegExp(`{[@$]${template}}`, "g"), templates[template]);
    }

    fs.writeFileSync("design-system.html", beautify(THE_HTML), "utf8");
    fs.writeFileSync("responsive.html", beautify(RESPONSIVE_HTML), "utf8");
    fs.writeFileSync("visual-library.html", beautify(THE_VISUAL_LIBRARY), "utf8");
});

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>BDO Components</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.7.5/beautify.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.7.5/beautify-css.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.7.5/beautify-html.js"></script>
    <script src="assets/js/libs.js" type="text/javascript"></script>

    <link rel="stylesheet" href="assets/css/assets-page.css" />
    <link rel="stylesheet" href="assets/css/component-guide.css" />
</head>

<body>

    <div class="display-panels">
        {$control-bar}

        <div class="preview-pane -hide-code">
            {$globals}
            {$design-references}
            {$component-modifiers}

            <div class="section-block element-group --show-code --components -component" 
                data-name="Typesetting">
                {$typesetting}
            </div>

            <div class="section-block element-group --show-code --components -component" 
                data-name="Elements">
                {$elements}
            </div>

            <div class="section-block element-group --show-code --components -component" 
                data-name="Low Level Components">
                {$low-level-components}
            </div>

            <div class="section-block element-group --show-code --components -component" 
                data-name="High Level Components">
                {$high-level-components}
            </div>

        </div>
        <div class="index-group">
        </div>
    </div>

    <script src="assets/js/app.js" type="text/javascript"></script>
</body>

</html>

2 个答案:

答案 0 :(得分:4)

您可以在readdir上使用名为fs的函数。它将返回一个文件名列表,您可以遍历该文件名并执行所需的任何操作。

基本上,这将读取dirname内的所有文件,读取返回的每个filename的内容,对其进行修改,然后将其写回。

(我用保证更好的流程包装了fs函数)

function readFiles(dirname) {
  let fileNames = [];
  let fileContents = [];
  const results = [];

  return readdir(dirname)
  .then((_fileNames) => {
    fileNames = _fileNames;

    // map filenames to array of readFile promises
    return Promise.all(fileNames.map((filename) => readFile(filename)))
  })
  .then((allFilesContent) => {
    fileContents = allFilesContent;

    // for each file, push an object with name + content to a new array
    fileNames.forEach((fileName, index) => {
      results.push({
        name: fileName, // <-- you can also change the file paths here if needed
        content: beautify(fileContents[index]) // <-- modify the content here as you please
      });
    });
  })
  // map that array to a writeFile promise array
  .then(() => results.map((file) => writeFile(file.name, file.content)))
  .then(() => console.log('all files written successfully'))
  .catch((err) => console.error(err));
}

// FS FUNCTIONS AS PROMISES:

function readFile(filepath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filepath, 'utf-8', function(err, content) {
      if (err) { return reject(err); }

      resolve(content); 
    });
  });
}

function readdir(dirname) {
  return new Promise((resolve, reject) => {
    fs.readdir(dirname, function(err, filenames) {
      if (err) { return reject(err); }

      resolve(filenames);
    });
  });
}

function writeFile(filename, content) {
  return new Promise((resolve, reject) => {
    fs.writeFile(filename, content, function(err) {
      if (err) { return reject(err); }

      resolve();
    });
  });
}

答案 1 :(得分:-1)

我有一系列模块(围绕递归地构造整个目录),然后做一些事情,例如制作一个网页,并显示结果。

添加所需的内容应该很容易。