ITeye博客

nodejs创建监听与获取封装对象模块

hy2012_campus · 2014-12-09 16:31 · js · 开源软件 · Markdown

整理与node.js开发指南

var http = require('http');
http.createServer(function(req,res){
     res.writeHead(200,{'Content-Type':'text/html'});
     res.write('<h1>node.js</h1>');
     res.end('<p>hello world</p>');
}).listen(3000);
console.log("http server is listening at port 3000.");

 运行node  app.js后进程不会退出事件循环 修改脚本都需要从新运行,因为只有在第一次才会被加载到内存中去。使用supervisor可以解决 当改动脚本时会自动重新运行。

创建模块和加载模块也是这样,reuqire不会重复夹在模块

有时候我们只是想把一个对象封装到模块中

function Hello(){
     var name;
     this.setName = function(thyName){
          name = thyName;
     };
     this.sayHello = function(){
          console.log('hello ' + name);
     };
};
exports.Hello = hello;

 此时我们在其他文件中通过require().hello来获取hello对象显得冗余,使用下面方法简化

function hello(){
     var name;
     this.setName = function(thyName){
          name = thyName;
     };
     this.sayHello = function(){
          console.log('hello' + name);
     };
};
module.exports = hello;

 

var Hello = require('./hello');
hello = new Hello();
hello.setName('BYVoid');
hello.sayHello();

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。