本文共 2006 字,大约阅读时间需要 6 分钟。
创建一个名为 module.js 的文件,内容如下:
// module.js var name; exports.setName = function(thyName) { name = thyName; }; exports.sayHello = function() { console.log('Hello ' + name); }; 在同一目录下创建 getmodule.js 文件,内容如下:
// getmodule.js var myModule = require('./module'); myModule.setName('BYVoid'); myModule.sayHello(); 运行 node getmodule.js,你会看到输出:
Hello BYVoid 通过上述示例可以看出,module.js 通过 exports 对象将 setName 和 sayHello 作为模块的接口提供。getmodule.js 文件通过 require('./module') 加载该模块,进而访问 exports 对象的成员函数。
为了简化这种情况,可以采用以下方法:将模块直接导出。例如:
module.exports = Hello;
这样一来,其他文件只需通过 require('./module').Hello 就可以直接访问 Hello 对象了。
npm i package 或 npm install package。npm i -g package。npm link package source dest。npm init。npm publish。这些命令可以帮助我们管理项目中的依赖,使开发和部署更加高效。
首先,安装 node-inspector:
npm install -g node-inspector
然后,在终端中启动调试服务器:
node-inspector
在浏览器中打开 http://127.0.0.1:8080/debug?port=5858,即可进行调试。
var util = require('util'); function Base() { this.name = 'base'; this.base = 1991; this.sayHello = function() { console.log('Hello ' + this.name); }; } Base.prototype.showName = function() { console.log(this.name); }; function Sub() { this.name = 'sub'; } util.inherits(Sub, Base); 通过 util.inherits,Sub 类继承了 Base 类原型中的方法,但不会继承 Base 构造函数内部定义的属性。
util.isArray()、util.isRegExp()、util.isDate() 和 util.isError()。util.format() 和 util.debug()。这些工具可以帮助开发者更好地理解和调试代码。
通过以上方法,我们可以更高效地开发和调试 Node.js 应用程序。
转载地址:http://fvjfk.baihongyu.com/