Im trying to create webpack loader for image processing. It should be pretty starightforward: find required modules with /.png$/ extension, write it to my test file. According to loader API, I recieve module`s content as a first argument of the loader function. But I don`t quite understand in what encoding I recieve it. PNG file is binary, as far as I know, but javascript strings are, by spec, UTF16 encoded.
I`ve written some code:
webpack.config.js
let path = require("path");
module.exports = {
entry: "./index.js",
output: {
filename: "bundle.js"
},
module:{
rules:[
{
test: /\.png$/i,
use: [
{
loader: path.resolve('./loader.js'),
}
]
}
]
},
watch: true
};
loader.js
let getOptions = require('loader-utils').getOptions;
var fs = require("fs");
module.exports = function(source){
fs.writeFileSync("my.png", source, "binary");
return "";
};
As far as I concerned, my initial thought was that I can do something like read source to Buffer and set it`s encoding as UTF-16, and then write this Buffer to the file, but that didn`t work.
The question is what should I do with source to write it to the file and create valid png from source. Cause right now all I`m getting is a bunch of errors like "cannot open file...".
I stumbled upon the answer and it is simply writing
module.exports.raw = true;
inside my loader. This way loader will really get raw buffer. Otherwise I get buffer recognized as if it was UTF-8 encoded. Pretty strange, considering tha javascript string are UTF-16 by spec