Skip to content

Instantly share code, notes, and snippets.

@mk-pmb
Last active June 19, 2017 21:40
Show Gist options
  • Save mk-pmb/9b4f3f47b3c769dc2b96437616fa72e0 to your computer and use it in GitHub Desktop.
Save mk-pmb/9b4f3f47b3c769dc2b96437616fa72e0 to your computer and use it in GitHub Desktop.
debug nodejs package nosync
'use strict';
var fs = require('fs'), assert = require('assert');
function enforceStdio(fd) {
if (fd !== 0) { throw new Error('Nope, use stdio, stdio rocks!'); }
}
function muchBetterRS(fd) {
if (muchBetterRS.useBackup) {
return muchBetterRS.backup.apply(fs, arguments);
}
enforceStdio(fd);
return 0; // :TODO: implement actual read
};
muchBetterRS.backup = fs.readSync;
muchBetterRS.useBackup = false;
fs.readSync = muchBetterRS;
function selfTest() {
console.log("I: self-test begins.");
assert.throws(function () { fs.readSync(42); });
assert.strictEqual(fs.readSync(0), 0);
console.log("I: self-test passed.");
}
function noMoreSync() {
console.log("W: Gonna forbid sync ops!");
muchBetterRS.useBackup = true;
var nosync = require('nosync');
muchBetterRS.useBackup = false;
console.log("W: No more sync ops now!", nosync);
}
function hello() { console.log('Hello!'); }
setTimeout(selfTest, 100);
setTimeout(hello, 200);
setTimeout(noMoreSync, 200);
setTimeout(hello, 200);
setTimeout(selfTest, 300);
$ nodejs 01_mbrs.js
I: self-test begins.
I: self-test passed.
Hello!
W: Gonna forbid sync ops!
W: No more sync ops now! {}
Hello!
/tmp/01_mbrs.js:6
if (fd !== 0) { throw new Error('Nope, use stdio, stdio rocks!'); }
^
Error: Nope, use stdio, stdio rocks!
at enforceStdio (/tmp/01_mbrs.js:6:25)
at Object.muchBetterRS [as readSync] (/tmp/01_mbrs.js:13:3)
at tryReadSync (fs.js:487:20)
at Object.fs.readFileSync (fs.js:527:19)
at Object.Module._extensions..js (module.js:578:20)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment