AGamePlayer
AGamePlayer

Reputation: 7734

Why the minify function returns Promise { <pending> } instead of the HTML when I require a global html-minifier?

I don't want to install the node modules again and again so I found a post here.

It uses npm link to let me require global packages.

However, when I use the method, the html-minifier-terser is not working properly. The minify function returns Promise { <pending> } instead of the HTML.

But it works fine with the same build.js while in that project, the pug and html-minifier-terser are install locally by npm install not npm install -g

Here is the code:

const fs = require('fs');
// Compile the source code
const pug = require('pug');
// Compile the source code


buildFile('index');

function buildFile(filename) {

  var fs_content = fs.readFileSync(`./data/page-${filename}.json`);
  var options = JSON.parse(fs_content);

  const compiledFunction = pug.compileFile(`./pugs/${filename}.pug`,{});

  // Render a set of data
  var pug_html = (compiledFunction(options)); // this works fine.
  var minify = require('html-minifier-terser').minify;
  var result = minify(pug_html, {
    removeAttributeQuotes: true,
    minifyJS:true,
    minifyCSS:true,
    removeComments:true,
    collapseWhitespace:true,
    collapseInlineTagWhitespace:true
  });
  console.log(result); // Returns Promise { <pending> } instead of the HTML
}

Update:

I tried await but it fails too:

  var result = await minify(pug_html, {
               ^^^^^

SyntaxError: await is only valid in async function
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)

Upvotes: 1

Views: 638

Answers (2)

HagenSR
HagenSR

Reputation: 11

See this link to learn more about promises. Essentially, you must wait for minifyJS to return the HTML by waiting for it (using .then((arg)=>{}). Also see the bottom of this readme

  minify(pug_html, {
    removeAttributeQuotes: true,
    minifyJS:true,
    minifyCSS:true,
    removeComments:true,
    collapseWhitespace:true,
    collapseInlineTagWhitespace:true
  }).then((res) => {result = res});

Upvotes: 0

Eisverygoodletter
Eisverygoodletter

Reputation: 173

Maybe it's an asynchronous function, and you need to do

var result = await minify(pug_html, {
    removeAttributeQuotes: true,
    minifyJS:true,
    minifyCSS:true,
    removeComments:true,
    collapseWhitespace:true,
    collapseInlineTagWhitespace:true
  });

with the await keyword, which makes it "wait" for the response from the function

Upvotes: 1

Related Questions