Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

require it is normal or not? #3404

Closed
alexander-akait opened this issue Oct 16, 2015 · 2 comments
Closed

require it is normal or not? #3404

alexander-akait opened this issue Oct 16, 2015 · 2 comments
Labels
question Issues that look for answers.

Comments

@alexander-akait
Copy link

for (var i = 0; i < 10; i++) {
    var jsonObject = require('file.json');

    functionChangeJsonObject(jsonObject);
}

First call require load file from filesystem, second call get this file from cache (reference on object). But my function(s) may be change this object. And second call require return changed object. It is normal behavior or not?

@Fishrock123
Copy link
Contributor

This is normal behavior. require() caches.

If you need to re-read it you'll need to use the fs module, probably fs.readFileSync(), though that won't be very efficient.

@Fishrock123 Fishrock123 added the question Issues that look for answers. label Oct 16, 2015
@Qard
Copy link
Member

Qard commented Oct 16, 2015

If you want a module to export a default state that multiple things can get unique copies of, you can export a function that you can call to return a new instance of the object.

Rather than this:

exports.foo = 'bar'

Do this:

module.exports = function () {
  return { foo: 'bar' }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Issues that look for answers.
Projects
None yet
Development

No branches or pull requests

3 participants