diff --git a/lib/node/fs.ts b/lib/node/fs.ts new file mode 100644 index 000000000..2871285b5 --- /dev/null +++ b/lib/node/fs.ts @@ -0,0 +1,56 @@ +import {bindArguments} from '../common/utils'; + +let fs; +try { + fs = require('fs'); +} catch (err) {} + +// TODO(alxhub): Patch `watch` and `unwatchFile`. +const TO_PATCH = [ + 'access', + 'appendFile', + 'chmod', + 'chown', + 'close', + 'exists', + 'fchmod', + 'fchown', + 'fdatasync', + 'fstat', + 'fsync', + 'ftruncate', + 'futimes', + 'lchmod', + 'lchown', + 'link', + 'lstat', + 'mkdir', + 'mkdtemp', + 'open', + 'read', + 'readdir', + 'readFile', + 'readlink', + 'realpath', + 'rename', + 'rmdir', + 'stat', + 'symlink', + 'truncate', + 'unlink', + 'utimes', + 'write', + 'writeFile', +]; + +if (fs) { + TO_PATCH + .filter(name => !!fs[name] && typeof fs[name] === 'function') + .forEach(name => { + fs[name] = ((delegate: Function) => { + return function() { + return delegate.apply(this, bindArguments(arguments, 'fs.' + name)); + }; + })(fs[name]); + }); +} diff --git a/lib/node/node.ts b/lib/node/node.ts index f0b057cd3..b9ef41c7b 100644 --- a/lib/node/node.ts +++ b/lib/node/node.ts @@ -2,6 +2,7 @@ import '../zone'; import {patchTimer} from '../common/timers'; import './events'; +import './fs'; const set = 'set'; const clear = 'clear'; diff --git a/test/node/fs.spec.ts b/test/node/fs.spec.ts new file mode 100644 index 000000000..8771509fb --- /dev/null +++ b/test/node/fs.spec.ts @@ -0,0 +1,13 @@ +import {exists} from 'fs'; + +describe('nodejs file system', () => { + it('has patched exists()', (done) => { + const zoneA = Zone.current.fork({ name: 'A' }); + zoneA.run(() => { + exists('testfile', (_) => { + expect(Zone.current.name).toBe(zoneA.name); + done(); + }); + }); + }); +}); \ No newline at end of file diff --git a/test/node_tests.ts b/test/node_tests.ts index e9ffdf416..c54060a2a 100644 --- a/test/node_tests.ts +++ b/test/node_tests.ts @@ -1 +1,2 @@ -import './node/events.spec'; \ No newline at end of file +import './node/events.spec'; +import './node/fs.spec'; \ No newline at end of file