Использование util.promisfy в скрипте сборки не работает должным образом - PullRequest
0 голосов
/ 02 октября 2018

У меня есть скрипт сборки в узле, который в один момент переписывает все ссылки ./src в ссылках на ссылки ./dist.Я читал на util.promisfy и пытался включить async / await в мой скрипт, но он не работает, как планировалось.Я могу переместить мои файлы в каталог / dist из / src и 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 голосов
/ 02 октября 2018

У вас есть это:

      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!";, даже если есть ошибка, поэтому я предлагаю сделать два оператора возврата: один внутри try и один внутри catch или использоватьfinally если это не имеет значения.

...