casualjavascript / blog

A collection of javascript articles stored as Github issues.
https://casualjavascript.com
MIT License
34 stars 1 forks source link

Self-spawning Node.js timer #5

Closed mateogianolio closed 8 years ago

mateogianolio commented 8 years ago

Originally posted 2015-12-24.

Hey, just because it's christmas I'll share a hack I found yesterday. Save the following code in a file named 1 (without extension) and run it with node 1. As an exercise, you could try to explain what will happen without reading the step by step below.

(function () {
  'use strict';

  var fs = require('fs'),
      spawn = require('child_process').spawn;

  function tick() {
    // 1
    var num = parseInt(__filename.split('/').pop());
    if (num >= 100)
      return;

    var name = String(num + 1);

    // 2
    var code = fs.readFileSync(__filename);

    // 3
    fs.unlinkSync(__filename);

    // 4
    fs.writeFileSync('./' + name, code);

    // 5
    spawn('node', [ name ]);

    // 6
    process.exit();
  }

  setTimeout(tick, 100);
}());

Step by step

  1. Parse number from filename
  2. Copy source of current file
  3. Remove current file
  4. Write source to a new file with the current number incremented by one
  5. Spawn a new process executing the new file
  6. Exit the current process

The result is a timer (I capped it at 100 to be nice to your computer) that'll count to 100 with its filename (make sure you have the directory open to see the effects).

Now try to exit the process(es) while running :)

Merry christmas.