Polymorphic / Genetic node.js code

What is polymorphic code? Polymorphic code is basically code that changes itself, under the condition that the new code is semantically the same (i.e. behaves the same).

As an example: console.log(42); console.log(21+21); console.log(21*2);
All those logs will output the same: 42. So they are semantically the same.

Okay, what can I use it for? Well I suggest you to take a look at Wikipedia for that, out of my head I can only come up with one scenario: Viruses. They can change the algorithm, while keeping the it semantically the same. Thus AntiVirus apps will have issues detecting them by only using their file md5 hash. Okay, okay. Nobody will write a virus with node.js - so just let this be for educational purpose.

fs = require('fs');
var file = __filename; // this is our own filename
fs.readFile(file, 'utf8', function (err,data) {
  data = data.substring(data.indexOf(";")+1); // remove console.log
  data = "console.log("+make42()+");"+data; // insert new console.log
  fs.writeFileSync(file, data); // write new modified code
function make42() {
  var i = Math.ceil(Math.random() * 100000);
  return i+"+"+(42-i); // rewrite 42 as a combination of numbers

This code will modify itself to replace the console.log(42) part with a linear combination of 2 numbers that summed up will be equal to 42.

Easy example, but you get the idea - and you can modify it easily.