require() should not be called as a constructor

  • CALL_REQUIRE_AS_CONSTRUCTOR
  • Error
  • Medium
  • nodejs

This rule applies when require() is called as a constructor with new operator.

When the instance creation code after loading the module is like new require('module').Module(), it is evaluated as (new require('module')).Module().
This causes an unsuccessful instance creation because the new operator does not apply for the constructor of the module.

In this case, explicit parentheses should be used like new (require('module').Module)().

Noncompliant Code Example

View with compliant examples side by side
var moduleInstance = new require('module').Module(); // CALL_REQUIRE_AS_CONSTRUCTOR alarm because 'new' operator is not applied for the constructor 'Module()'.

Compliant Code Example

View with noncompliant examples side by side
var moduleInstance = new (require('module').Module)();

Version

This rule was introduced in DeepScan 1.11.0-beta.

Was this documentation helpful?