Skip to content

fs, cjs modules: failed require prevents valid require from loading a module just written by writeFileSync #36638

Description

@vsemozhetbyt
  • Version: 15.5.0
  • Platform: Windows 10 x64
  • Subsystem: fs, cjs modules

What steps will reproduce the bug?

It seems there may be some race conditions.

Error (cannot find module...):

const fs = require('fs');

try { require('./test.json'); } catch (err) {}

fs.writeFileSync('test.json', '[]');
console.log(require('./test.json'));

With timeout — OK:

const fs = require('fs');

try { require('./test.json'); } catch (err) {}

fs.writeFileSync('test.json', '[]');
setTimeout(() => { console.log(require('./test.json')); }, 1000);

With callback — OK:

const fs = require('fs');

try { require('./test.json'); } catch (err) {}

fs.writeFile('test.json', '[]', () => { console.log(require('./test.json')); });

Promisified — OK:

const fs = require('fs/promises');

try { require('./test.json'); } catch (err) {}

(async function(path) {
  await fs.writeFile('test.json', '[]');
  console.log(require('./test.json'));
})();

Without failed try — OK:

const fs = require('fs');

fs.writeFileSync('test.json', '[]');
console.log(require('./test.json'));

Previously reported in nodejs/help#3144

Activity

  1. added
    moduleIssues and PRs related to the module subsystem.
    on Dec 26, 2020
  2. BridgeAR commented on Dec 27, 2020

    @BridgeAR
    Member

    It's not a race condition. All sync require calls use a single cache that's invalidated afterwards. Thus, as soon as there's anything async, the file is possible to be found.

  3. GrosSacASac commented on Jan 11, 2021

    @GrosSacASac
    Contributor

    Maybe require should not be cached on failure

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

    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