码迷,mamicode.com
首页 > Web开发 > 详细

Node.js入门(一)

时间:2015-05-20 00:08:57      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

一、Node.js环境配置:

http://www.w3cschool.cc/nodejs/nodejs-install-setup.html

 

 

二、命令行控制(cmd/命令提示符):

1.读取文件方式:

C:\User\UserName>

C:\User\UserName>E:  //你的node项目文件夹所在的磁盘

E:\>cd\node  //我的node文件都放在node文件夹下

E:>node>node server.js

2.交互模式:

C:\User\UserName>

C:\User\UserName>E:  

E:\>cd\node

E:>node>node

>console.log(‘Hello World!‘);

Hello World!

undefined

 

 

三、Node.js创建HTTP服务器

1.在你的项目的根目录下创建一个叫 server.js 的文件,并写入以下代码:

var http = require(‘http‘); //请求Node.js自带的http模块

http.createServer(function (request,response){  //createServer()是http模块自带的方法,这个方法会返回一个对象,此对象的listen()方法,传入这个 HTTP 服务器监听的端口号。
  response.writeHead(200,{‘Content-Type‘:‘text/plain‘});
  response.end(‘Hello World\n‘);
}).listen(8888);

console.log(‘Server running at http://127.0.0.1:8888/‘);

这样就完成了一个可以工作的 HTTP 服务器。

2.使用 node命令 执行以上的代码:

E:>node>node server.js

Server running at http://127.0.0.1:8888/

3.接下来,打开浏览器访问 http://127.0.0.1:8888/,你会看到一个写着 "Hello World"的网页。

技术分享

 

 

四、Node.js模块

 

Node.js 提供了exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。

 

1.创建一个 ‘main.js‘ 文件,代码如下:

var hello = require(‘./hello‘);  //引入了当前目录下的hello.js文件(./ 为当前目录,node.js默认后缀为js)。

hello.world();

2.创建一个 ‘hello.js‘文件,此文件就是hello模版文件,代码如下:

exports.world = function (){  //exports 是模块公开的接口
  console.log(‘Hello world‘);
};

 

3.把对象封装到模块中:

module.exports = function (){

  // . . .

};

例如:

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

这样就可以直接获得这个对象了:

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

 

 

 

Node.js入门(一)

标签:

原文地址:http://www.cnblogs.com/liuqiuchen/p/4515788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!