I remembered about quines today and as I hadn't ever written one before, I decided to write a quine in javascript for node.js. A quine is a computer program which takes no input and produces a copy of its own source code as its only output.

Turns out it was easier than expected. The key idea in writing a quine is having data that contains the whole program, which is then modified to match the program and printed.

Here is how my quine for node.js looks:

var data = "module.exports = function () { console.log(\"var data = \\\"%s\\\"\

%s\", data.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, \"\\\\\\\"\"), data.replace(/{/, \"{\

\").replace(/}$/, \"\

}\")); }" module.exports = function () { console.log("var data = \"%s\"

%s", data.replace(/\\/g, "\\\\").replace(/"/g, "\\\""), data.replace(/{/, "{

").replace(/}$/, "

}")); }

If you require this module and call the exported function, you get the same module back:

> require('./index.js')()

Output:

var data = "module.exports = function () { console.log(\"var data = \\\"%s\\\"\

%s\", data.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, \"\\\\\\\"\"), data.replace(/{/, \"{\

\").replace(/}$/, \"\

}\")); }" module.exports = function () { console.log("var data = \"%s\"

%s", data.replace(/\\/g, "\\\\").replace(/"/g, "\\\""), data.replace(/{/, "{

").replace(/}$/, "

}")); }

Node-quine on my github: https://github.com/pkrumins/node-quine.

Update

Turns out a quine in node.js that prints itself can be written much simpler this way (by maciejmalecki):

function quine() { console.log(quine.toString()) }

SubStack came up with this solution:

(function f() { console.log('(' + f.toString() + ')()') })()

And here is Erik Lundin's quine:

module.exports = function () { console.log('module.exports = ' + arguments.callee.toString()); }

Isaacs offers this version of qunie that adds cli support. However this doesn't count as quine is not allowed to read the source file of itself. But I'm including it here anyway as it's fun:

var data = require('fs').readFileSync(module.filename, 'utf8'); module.exports = function () { console.log(data); }; if (module === require.main) module.exports();

Hooray for quines!