Skip to content

Odd behaviour: createRequireFromPath('.') #27401

Description

@SMotaal
  • Version: v12.0.0
  • Platform: macOS 10.14.4
  • Subsystem: module

Calling createRequireFromPath('.') does not honour process.cwd() when called a second time after an effective call to process.chdir(…).

Best explained by this: https://github.com/SMotaal/esm/blob/master/tests/create-require.mjs#L8

Details
import {createRequireFromPath} from 'module';
import {fileURLToPath} from 'url';

const specifier = './package.json';
const [scope, ...paths] = ['../../', '../', './'].map(path => fileURLToPath(new URL(path, import.meta.url)));
const sanitize = path => path.replace(scope, '‹scope›/');

for (const path of process.argv.includes('-t2') ? paths.reverse() : paths) {
  process.chdir(path);
  console.group('\nprocess.chdir(%o)', sanitize(process.cwd()));
  console.log();
  try {
    const require = createRequireFromPath('.');
    console.log(
      `createRequireFromPath(%o)\n  .resolve(%o)\n    => %o`,
      '.',
      specifier,
      sanitize(require.resolve(specifier)),
    );
  } catch (exception) {
    console.warn(
      `createRequireFromPath(%o)\n  .resolve(%o)\n    => %o`,
      '.',
      specifier,
      `${exception}`.split('\n', 1)[0],
    );
  }
  console.log();
  console.groupEnd();
}

/*******************************************************************************
 * $ node --experimental-modules esm/tests/create-require.mjs
 *
 *   process.chdir('‹scope›/esm/')
 *
 *     createRequireFromPath('.')
 *       .resolve('./package.json')
 *         => '‹scope›/esm/package.json'
 *
 *   process.chdir('‹scope›/esm/tests/')
 *
 *     createRequireFromPath('.')
 *       .resolve('./package.json')
 *         => '‹scope›/esm/package.json'
 *
 ******************************************************************************
 * $ node --experimental-modules esm/tests/create-require.mjs -t2
 *
 *   process.chdir('‹scope›/esm/tests/')
 *
 *     createRequireFromPath('.')
 *       .resolve('./package.json')
 *         => '‹scope›/esm/tests/package.json'
 *
 *   process.chdir('‹scope›/esm/')
 *
 *     createRequireFromPath('.')
 *       .resolve('./package.json')
 *         => '‹scope›/esm/tests/package.json'
 *
 ******************************************************************************/

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestIssues requesting new Node.js features.moduleIssues and PRs related to the module subsystem.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions