Wednesday, 10 May 2017

node.js replace() - Invalid string length error

I've just coded a little script to replace all variables from a .txt file to their values in a JS file

Example:

Txt file example (values):

Hi = "HELLO WORLD",
Hey = /someregex/g,
Hh = 'haha';

Script example:

window[Hi] = true;

"someregex hi".replace(Hey, "")

window[Hh] = 1;

Here's my script:

var fs = require("fs")


var script = fs.readFileSync("./script.js", "utf8");
var vars   = fs.readFileSync("./vars.txt", "utf8");

var replace = {}

var spl = vars.replace(/\r\n/g, "").replace(/        /g, "").split(",");

console.log("caching variables")

for(var dt of spl) {
    var splt = dt.split(" = ");

    var name = splt[0];
    var val  = splt[1];

    if(!name || !val) {
        continue;
    }

    if(val.endsWith(";")) {
        val = val.slice(0, -1);
    }

    replace[name] = val;
}

console.log("Variables are in cache!")
console.log("Replacing variables in script")

var i = 1;
var t = Object.keys(replace).length;

for(var var_name in replace) {
    var var_val = replace[var_name];
    var regex   = new RegExp(var_name, "g");

    console.log(i, "/", t, "Replacing", var_name, "with", var_val, "regex", regex)

    script = script.replace(regex, var_val);

    i++;
}

console.log("DONE!")

fs.writeFileSync("./dec.js", script, "utf8")

However, when i ~= 100, I have this error:

RangeError: Invalid string length
    at RegExp.[Symbol.replace] (native)
    at String.replace (native)

EDIT: also, I can see that node.js process is using ~400MB of RAM and I have the error when it reaches 900MB

What's wrong?



via JeePing

No comments:

Post a Comment