首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在构建脚本中使用util.promisfy不像预期的那样工作

在构建脚本中使用util.promisfy不像预期的那样工作
EN

Stack Overflow用户
提问于 2018-10-02 17:09:09
回答 1查看 485关注 0票数 1

我在节点中有一个构建脚本,它可以在链接中重写到./dist引用的所有./src引用。我一直在阅读util.promisfy,并尝试将异步/等待集成到我的脚本中,但它没有按计划工作。我可以将我的文件从/dist目录中移到/src和uglify index.js,并压缩图像ok,但是使用节点fs函数来读取和写入/src文件更新链接是行不通的。下面是build.js的相关部分:

代码语言:javascript
复制
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

校正后更新的控制台读出:控制台读出如下:

代码语言:javascript
复制
    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 !]

内容现在为空白。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-02 17:18:41

你有这个:

代码语言:javascript
复制
      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"); 
          }
        }
      );

但是,如果对其进行了改进,则不存在错误回调函数。简单地说:

代码语言:javascript
复制
      await copyFileAsync(
        "./index.html",
        fs.constants.R_OK | fs.constants.W_OK
      )
      await fc("./index.html", "./dist/index.html");

您的尝试/捕捉将得到错误。

另外,即使有错误,也总是返回try/catch return "Copied Index.html to /dist!";,所以我建议创建两个返回语句,一个在try中,一个在catch中,或者使用finally (如果不重要的话)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52613160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档