nodejs学习一

1.第一个Node.js程序:Hello World!
新建js文件helloworld.js,内容输入console.log("Hello World");然后命令行输入node helloworld.js    
2.Node.js 创建HTTP服务器
var http =require('http');
http.createServer(function(request, response) {
    var retHtml = "<html><head><tittle>Node.js Test</tittle></head><body><div>Hi Node,I like you so mush</div></body>"
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end(retHtml);
    //response.end('Hello World\n');}).listen(8888,"127.0.0.1");
}).listen(8888,"127.0.0.1");
console.log('Server running at http://127.0.0.1:8888/');
接下来,打开浏览器访问 http://127.0.0.1:8888/,你会看到一个写着 "Hello World"的网页。
  
  
  • 第一行请求(require)Node.js 自带的 http 模块,并且把它赋值给 http 变量。
  • 接下来我们调用 http 模块提供的函数: createServer 。这个函数会返回 一个对象,这个对象有一个叫做 listen 的方法,这个方法有一个数值参数, 指定这个 HTTP 服务器监听的端口号。
3.Node.js模块系统
为了让Node.js的文件可以相互调用 ,Node.js提供了一个简单的模块系统。
模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。换言之,一个 Node.js 文件就是一个模块,这个文件可能是JavaScript 代码、JSON 或者编译过的C/C++ 扩展。
Node.js 提供了exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。
//hello.js functionHello(){var name;this.setName =function(thyName){ 
		name = thyName;};this.sayHello =function(){ 
		console.log('Hello '+ name);};};module.exports =Hello;
//main.js varHello=require('./hello'); 
hello =newHello(); 
hello.setName('BYVoid'); 
hello.sayHello();
不懂require深层次操作
Node.js中存在4类模块(原生模块和3种文件模块)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值