0

I would like to use this npm module to compress files, but I'm a bit stuck by the documention.

In a linux shell :

npm install brotli # npm@4.1.2 # brotli@1.3.1 

node # v6.9.4

Then inside node:

var fs = require('fs');
var brotli = require('brotli');

brotli.compress(fs.readFileSync('myfile.txt')); // output is numbers

fs.writeFile('myfile.txt.br', brotli.compress(fs.readFileSync('bin.tar')), function(err){ if (!err) { console.log('It works!');}});
"It works!"

But the file is full of numbers too...

I've never used streams and fs like that in node, can someone explains how to deal with this? Thanks!

Ratnoz
  • 125
  • 1
  • 6
  • what exactly are you trying to achieve? If the file looks something like it is correct as you are compressing the buffer that returns from `fs.readFileSync('myfile.txt')` and writing it to another file. If you want to see the decoded buffer you need to decompress it before writing to disk – Gabs Jan 27 '17 at 15:09
  • I have to compress files with node (and use the brotli compression as it's cool :) ). In a shell I would have used the "bro" command from the compiled project, but here I don't have access to it. – Ratnoz Jan 27 '17 at 22:31
  • if you don't specify an encoding type, node.js will use utf-8 by default. Not sure if this would work but try using binary instead. `fs.writeFile('myfile.txt.br', brotli.compress(fs.readFileSync('bin.tar')), 'binary', function(err){ if (!err) { console.log('It works!');}});` – Gabs Jan 30 '17 at 13:02
  • The problem was indeed that I did'nt put any settings/encoding type like `'binary'` or the object in the answer below. – Ratnoz Sep 19 '19 at 13:39

1 Answers1

0

With this simple JS code you are compressing each *.html *.css *.js file inside the folder you choose (in this case /dist)

const fs = require('fs');
const compress = require('brotli/compress');

const brotliSettings = {
    extension: 'br',
    skipLarger: true,
    mode: 1, // 0 = generic, 1 = text, 2 = font (WOFF2)
    quality: 10, // 0 - 11,
    lgwin: 12 // default
};

fs.readdirSync('dist/').forEach(file => {
    if (file.endsWith('.js') || file.endsWith('.css') || file.endsWith('.html')) {
        const result = compress(fs.readFileSync('dist/' + file), brotliSettings);
        fs.writeFileSync('dist/' + file + '.br', result);
    }
});
Ferie
  • 1,358
  • 21
  • 36
  • Thanks! But there is a typo in your import, either write `const brotli = require('brotli');` (line 2) or remove the `brotli.` (line 14). – Ratnoz Sep 19 '19 at 13:16