美文网首页
nodejs运用

nodejs运用

作者: Mx勇 | 来源:发表于2016-11-28 13:57 被阅读12次

一  nodejs基本格式

//步骤一:引入require模块,require指令载入http模块

var http = require('http');

//步骤二:创建服务器

http.createServer(function (request, response) {

// 发送 HTTP 头部

// HTTP 状态值: 200 : OK

// 内容类型: text/html

response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'});

//步骤三:接受请求与响应请求

if(request.url!=='/favicon.ico'){

......

// 发送响应数据

response.end('');//必须有,没有则没有协议尾

}

}).listen(8000);

// 终端打印如下信息

console.log('Server running at http://127.0.0.1:8000/');

nodejs调用函数

-----------------调用本地函数-----------------------------

var http = require('http');

http.createServer(function (request, response) {

response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'});

if(request.url!=='/favicon.ico'){

fun1(response);

// 发送响应数据

response.end('');

}

}).listen(8000);

// 终端打印如下信息

console.log('Server running at http://127.0.0.1:8000/');

function  fun1(res){

console.log('fun1');

res.write('hello,我是fun1');

}

-----------------调用外部函数-----------------------------

注意:外部函数必须写在module.exports中,exports 是模块公开的接口

------------(1)仅调用一个函数-----------

主程序中:

var http = require('http');

var  otherfun = require("./models/otherfuns.js");//调用外部页面的fun2

http.createServer(function (request, response) {

response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'});

if(request.url!=='/favicon.ico'){

otherfun(response);//支持一个函数时

response.end('');

}

}).listen(8000);

// 终端打印如下信息

console.log('Server running at http://127.0.0.1:8000/');

otherfuns.js中

function  fun2(res){

console.log('fun2');

res.write('你好!,我是fun2');

}

module.exports = fun2;//只支持一个函数

------------(2)调用多个函数-----------

主程序中:

var http = require('http');

var  otherfun = require("./models/otherfuns.js");//调用写函数的外部页面otherfuns.js

http.createServer(function (request, response) {

response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'});

if(request.url!=='/favicon.ico'){

//todo 以对象.方法名调用

otherfun.fun2(response);

otherfun.fun3(response);

//todo 以字符串调用对应函数(结果同上)

//otherfun['fun2'](response);

//otherfun['fun3'](response);

response.end('');

}

}).listen(8000);

// 终端打印如下信息

console.log('Server running at http://127.0.0.1:8000/');

}

otherfuns.js中

module.exports={

fun2:function(res){//匿名函数

console.log('fun2');

res.write('你好!,我是fun2');//在页面中输出

},

fun3:function(res){

console.log('fun3');

res.write('你好!,我是fun3');

},

......

}

相关文章

网友评论

      本文标题:nodejs运用

      本文链接:https://www.haomeiwen.com/subject/dadopttx.html