var minify = require('html-minifier').minify;
const fs = require('fs');
var dir = './minifiedHTML';
Try consistently using const
, let
or var
when declaring variables. Also, try using const
first. That way, you're ensured that you are always dealing with the same thing through that variable throughout the lifetime of the app, and that any attempts to replace it would warn you. Use let
if the value needs replacing (i.e. a counter) and var
if the variable has to be function-scoped.
fs.writeFile('minifiedHTML/minified.html', result, (err) => {
// throws an error, you could also catch it here
if (err) throw err;
// success case, the file was saved
console.log('HTML file saved!');
});
You're using synchronous APIs for everything except when writing to the file. I recommend also using the synchronous version of writing to a file, fs.writeFileSync()
to keep it consistent. Your script is simple, and it's not blocking anything else, so making everything synchronous should be fine.
I'm making a big guess. You're trying to embed this HTML in JSON or JavaScript, and you're escaping the quotes so that it won't terminate the script mid-string. If possible, don't embed HTML (or any arbitrary string really). Just have it carry data, and let the receiving page do the rendering instead. Or you could encode the data in base64 so that it doesn't have quotes at all.
My initial guess was not that far from the intended goal. Building JSON with HTML content IS NOT an issue if you're building the JSON correctly. JSON.stringify()
will correctly escape content that would otherwise break the resulting JSON (i.e. it will escape quotes). The only time escaping becomes an issue is when you're building the JSON manually.
Do NOT do the following:
const title = 'your title'
const subject = 'your subject'
const html = '<html lang="en"><body class="has-content">Hello, World!</body></html>'
const json = `{ "title": "${title}", "subject": "${subject}", "html": "${html}" }`
console.log('Invalid JSON:', json)
// This will blow up
console.log('Test parse', JSON.parse(json))
Instead, use JSON.stringify()
:
const title = 'your title'
const subject = 'your subject'
const html = '<html lang="en"><body class="has-content">Hello, World!</body></html>'
const json = JSON.stringify({ title, subject, html })
console.log('Valid JSON:', json)
console.log('Test parse', JSON.parse(json))