---
title: "nodejs创建监听与获取封装对象模块"
author: "hy2012_campus"
date: "2014-12-09T16:31:47Z"
tags: []
categories: ["开源软件"]
slug: "nodejs"
draft: false
lastmod: "2014-12-09T17:16:55Z"
id: 2164575
url: "https://hy2012.iteye.com/blog/2164575"
---

整理与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();
```