关于 Nodejs 模块的错误
An Error about Nodejs module
我是 Nodejs 的初学者,我按照指南学习这个。现在,我有了一个module.js
function Hello()
{
var name;
this.setName=function(thyName){
name=thyName;
};
this.sayHello=function()
{
console.log("hello,"+name);
};
};
module.exports=Hello;
和getModule.js
var hello = require("./module");
hello.setName("HXH");
hello.sayHello();
但是当我跑步时:
d:'nodejs'demo>node getModule.js
我收到错误:
d:'nodejs'demo'getModule.js:2
hello.setName("HXH");
^
TypeError: Object function Hello()
{
var name;
this.setName=function(thyName){
name=thyName;
};
this.sayHello=function()
{
console.log("hello,"+name);
};
} has no method 'setName'
at Object.<anonymous> (d:'nodejs'demo'getModule.js:2:7)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
为什么我得到这个?我只是按照指南进行操作。
我不确定您遵循的指南是什么,但module.js
导出一个类。由于module.js
导出了一个类,因此当您执行require('./module')
时,您将获得一个类。但是,您正在使用您获得的该类,就好像它是该类的实例一样。如果你想要一个实例,你需要使用如下new
:
var Hello = require('./module'); // Hello is the class
var hello = new Hello(); // hello is an instance of the class Hello
hello.setName("HXH");
hello.sayHello();
首先,NodeJS遵循CommonJS规范来实现模块。你应该知道它是如何工作的。
其次,如果你想像你编写的方式一样使用模块,你应该修改你的module.js
和getModule.js
如下:
//module.js
module.exports.Hello= Hello;
//getModule.js.js
var Hello = require("./module");
var hello = new Hello();
hello.setName("HXH");
hello.sayHello();
相关文章:
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- 错误:$injector:modulerr模块错误(我的第一个SPA应用程序)
- Babel编译错误:找不到模块核心js/library/fn/get迭代器
- 因果报应-找不到模块:错误:无法解析模块'scs'
- 错误:找不到模块'/lib/cli'
- 错误:$injector:modulerr加载图像时模块处于角度
- 扩展错误es6类模块问题
- 获取错误模块“;反应”;找不到
- 未捕获错误:模块未自注册
- 错误:模块未自行注册
- 离子 + 火基,错误模块“火基”不可用
- 如何在angular js中包含模块以删除找不到的错误模块
- AngularJS错误:模块'ngResource'不可用!您要么拼错了模块名称,要么忘记加载它
- 未捕获错误:模块名称“”;twilio”;尚未加载
- Firebase, AngularFire错误:模块Firebase不可用
- 未捕获错误:模块名"gcm"尚未加载上下文:_.使用要求([])
- RequireJS定义了返回错误模块依赖的回调
- 绑定错误.模块没有自我注册
- 当我运行“npm run dev”时,出现错误:模块解析失败
- npm启动错误"模块未找到;错误:无法解析目录"