在构建脚本中使用util.promisfy无法正常工作

时间:2018-10-02 17:09:10

标签: node.js async-await fs

我在节点中有一个构建脚本,该脚本一次重写了指向./dist引用的链接中的所有./src引用。我一直在阅读util.promisfy,并尝试将async / await合并到我的脚本中,但是它没有按计划工作。我可以将文件从/ src移动到/ dist目录,然后uglify index.js并压缩图像,但是可以使用节点fs函数读取和写入index.html文件来更新链接不起作用。这是build.js的相关部分:

const fs = require("fs");
const fc = require("file-copy");
const { promisify } = require("util");
const copyFileAsync = promisify(fs.access); // convert fs.access to a promise
const readFileAsync = promisify(fs.readFile); // convert fs.readFile to a promise
const confirmWriteAsync = promisify(fs.stat); // convert fs.stat to a promise;
const writeFileAsync = promisify(fs.writeFile); // convert fs.writeFile to a promise

const mkdirp = require("mkdirp");
       // Compressed and uglified files here ok //

      // ============ Copy index.html to dist/index.html(copyIndexHtml) ============ //
      /* jshint ignore:start */
      const copyIndexFile = async function(result) {
    try {
      console.log(result);
      await copyFileAsync(
        "./index.html",
        fs.constants.R_OK | fs.constants.W_OK
      )
      await fc("./index.html", "./dist/index.html");
    } catch (err) {
      console.log("ERROR:", err);
        }
        return "Copied Index.html to /dist!";
      }; // end copyIndexFile
      /* jshint ignore:end */

      // ================== End copyIndexFile ================ //

      // ====== Read data from dist/index.html(getData) =============== //


      /* jshint ignore:start */
      const getData = async function(result) {
        console.log(result);

        // Lets update dist/index.html file src and href links to reflect new location. 
        console.log(
          "index.html: Redoing file links to reflect move to /dist folder."
        );
        try {
          const fileContents = await readFileAsync("./dist/index.html", {
            encoding: "utf8"
          });
          console.log("CONTENT:", fileContents);

          // check and replace both src= and href= links to reflect chenge to dist/ folder
          // Notice we chained .replace to do it
          const regEx1 = /src\s*=\s*"\.\/src\//gi;
          const regEx2 = /src\s*=\s*'\.\/src\//gi;
          const regEx3 = /href\s*=\s*"\.\/src\//gi;
          const regEx4 = /href\s*=\s*'\.\/src\//gi;

          let distIndexHtml = fileContents
            .replace(regEx1, 'src="./')
            .replace(regEx2, "src='./")
            .replace(regEx3, 'href="./')
            .replace(regEx4, "href='./");

          console.log(distIndexHtml);

          // Confirm Write to index.html
          await confirmWriteAsync("./dist/index.html", function(err, stats) {
            if (err) {
              console.log(`Error: ${err}`);
            } else if (stats.size === 0) {
              console.log(`Error copying index.html!!!!!!`);
            } else {
              console.log(
                `Succesfully copied to dist\index.html. File size is ${
                  stats.size
                }`
              );
            }
          });

          await writeFileAsync(
            "dist/index.html",
            distIndexHtml,
            "utf8",
            err => {
              if (err) {
                reject(err);
              } else {
                resolve("Write to dist//index.html OK.");
              }
            }
          );
        } catch (err) {
          console.log("ERROR:", err);
        }
        return "Read /dist/index.html file!!";
      };
      /* jshint ignore:end */

      // ==================================================== //
      // ========== Call promise chain ====================== //
      // ==================================================== //
      browserifyJS()
        .then(
          result => {
            return compressImages(result);
          },
          err => {
            console.log(err);
            return compressImages(err);
          }
        )
        .then(result => {
          return copyIndexFile(result);
        })
        .then(result => {
          return getData(result);
        })
        .then(result => {
          console.log(result);
        });
    } // mkdirp else end
  }); // mkdirp callback end
}); // rimraf callback end

更正后更新的控制台读数:控制台读数为:

    npm run build

> sports-page-app@1.0.0 build C:\Users\akillian\Local Documents\GitHub\sports-page-app
> node ./scripts/build

main.css: build and uglify
Checking for index.js
Bundling Successful!
Images Compressed!!!
/dist/index.js: build and uglify
Copied Index.html to /dist!
index.html: Redoing file links to reflect move to /dist folder.
CONTENT:

Succesfully copied to distindex.html. File size is 3059
~\Local Documents\GitHub\sports-page-app [refactor-app ≡ +0 ~1 -0 !]

CONTENT现在为空。

1 个答案:

答案 0 :(得分:1)

你有这个:

      await copyFileAsync(
        "./index.html",
        fs.constants.R_OK | fs.constants.W_OK,
        err => {
          if (err) {
            console.log("No index.html file present!");
          } else {
            // Note: fc() returns a promise and no .catch()
            // This also means the code continues on without
            // waiting for the file to copy.
            fc("./index.html", "./dist/index.html"); 
          }
        }
      );

但是,如果您承诺,则不会有错误回调函数。 简单地:

      await copyFileAsync(
        "./index.html",
        fs.constants.R_OK | fs.constants.W_OK
      )
      await fc("./index.html", "./dist/index.html");

,您的try / catch将得到错误。

即使有错误,也总是使用特定的try / catch return "Copied Index.html to /dist!";返回,所以我建议做出两个return语句,一个在try内部,另一个在catch内部或者不要紧使用finally