• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common');
3
4// This tests the creation of a vfs by monkey-patching fs and Module._stat.
5
6const Module = require('module');
7const fs = require('fs');
8const tmpdir = require('../common/tmpdir');
9const { deepStrictEqual, ok, strictEqual, throws } = require('assert');
10const { join } = require('path');
11
12const directory = join(tmpdir.path, 'directory');
13const doesNotExist = join(tmpdir.path, 'does-not-exist');
14const file = join(tmpdir.path, 'file.js');
15
16tmpdir.refresh();
17fs.writeFileSync(file, "module.exports = { a: 'b' }");
18fs.mkdirSync(directory);
19
20strictEqual(Module._stat(directory), 1);
21ok(Module._stat(doesNotExist) < 0);
22strictEqual(Module._stat(file), 0);
23
24const vfsDirectory = join(process.execPath, 'directory');
25const vfsDoesNotExist = join(process.execPath, 'does-not-exist');
26const vfsFile = join(process.execPath, 'file.js');
27
28ok(Module._stat(vfsDirectory) < 0);
29ok(Module._stat(vfsDoesNotExist) < 0);
30ok(Module._stat(vfsFile) < 0);
31
32deepStrictEqual(require(file), { a: 'b' });
33throws(() => require(vfsFile), { code: 'MODULE_NOT_FOUND' });
34
35common.expectWarning(
36  'ExperimentalWarning',
37  'Module._stat is an experimental feature and might change at any time'
38);
39
40process.on('warning', common.mustCall());
41
42const originalStat = Module._stat;
43Module._stat = function(filename) {
44  if (!filename.startsWith(process.execPath)) {
45    return originalStat(filename);
46  }
47
48  if (filename === process.execPath) {
49    return 1;
50  }
51
52  switch (filename) {
53    case vfsDirectory:
54      return 1;
55    case vfsDoesNotExist:
56      return -2;
57    case vfsFile:
58      return 0;
59  }
60};
61
62const originalReadFileSync = fs.readFileSync;
63// TODO(aduh95): We'd like to have a better way to achieve this without monkey-patching fs.
64fs.readFileSync = function readFileSync(pathArgument, options) {
65  if (!pathArgument.startsWith(process.execPath)) {
66    return originalReadFileSync.apply(this, arguments);
67  }
68  if (pathArgument === vfsFile) {
69    return "module.exports = { x: 'y' };";
70  }
71  throw new Error();
72};
73
74fs.realpathSync = function realpathSync(pathArgument, options) {
75  return pathArgument;
76};
77
78strictEqual(Module._stat(directory), 1);
79ok(Module._stat(doesNotExist) < 0);
80strictEqual(Module._stat(file), 0);
81
82strictEqual(Module._stat(vfsDirectory), 1);
83ok(Module._stat(vfsDoesNotExist) < 0);
84strictEqual(Module._stat(vfsFile), 0);
85
86strictEqual(Module._stat(process.execPath), 1);
87
88deepStrictEqual(require(file), { a: 'b' });
89deepStrictEqual(require(vfsFile), { x: 'y' });
90