赋值给导出变量¶
ID: js/node/assignment-to-exports-variable
Kind: problem
Security severity:
Severity: warning
Precision: very-high
Tags:
- maintainability
- frameworks/node.js
- external/cwe/cwe-563
Query suites:
- javascript-security-and-quality.qls
仅导出单个值的 Node.js 模块通常通过直接将其赋值给module.exports
属性来实现。一个常见的错误是将其赋值给exports
变量,但这只是覆盖了exports
的值,而不会影响module.exports
的值,并且不会导致任何内容被导出。
建议¶
重写赋值语句,使其赋值给module.exports
。
示例¶
在以下示例中,模块point.js
试图通过将其赋值给exports
来导出函数Point
。如上所述,这不会按预期工作:在赋值之后,exports
变量将包含对Point
的引用,但module.exports
属性仍然包含对空对象的引用。因此,client.js
中的客户端代码将失败,因为它试图将对象作为构造函数调用。
// point.js
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.distance = function() {
return Math.sqrt(this.x*this.x+this.y*this.y);
};
exports = Point;
// client.js
var Point = require('./point');
var pyth = new Point(3, 4);
console.log(pyth.distance());
不要赋值给exports
,而应该赋值给module.exports
。
// point.js
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.distance = function() {
return Math.sqrt(this.x*this.x+this.y*this.y);
};
module.exports = Point;
// client.js
var Point = require('./point');
var pyth = new Point(3, 4);
console.log(pyth.distance());
参考¶
Node.js 手册:exports 别名。
常见弱点枚举:CWE-563。