hello world
var http = require(‘http‘); //请求协议
http.createServer(function (request, response) {
response.writeHead(200, {‘Content-Type‘: ‘text/html; charset=utf-8‘}); //请求头信息,定义的文本类型和字符集
if(request.url!=="/favicon.ico"){ //清除第2此访问
console.log(‘访问‘);
response.write(‘hello,world‘);
response.end(‘hell,世界‘);//不写则没有http协议尾,但写了会产生两次访问
}
}).listen(8000);
console.log(‘Server running at http://127.0.0.1:8000/‘);
/*
启动服务
cmd下执行:
node n1_hello.js
浏览器访问:http://localhost:8000
*/
-----------------------------------------------------------------------------------------------------
node.js调用函数
1.本地函数
var http = require(‘http‘);
http.createServer(function (request, response) {
response.writeHead(200, {‘Content-Type‘: ‘text/html; charset=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");
}
2.调用其他js文件的函数
na_node.js
var http = require(‘http‘);
var otherfun = require("./model/otherfun.js");//插入其他js文件
http.createServer(function (request, response) {
response.writeHead(200, {‘Content-Type‘: ‘text/html; charset=utf-8‘});
if(request.url!=="/favicon.ico"){
//otherfun(response);
//otherfun.fun2(response);//可以直接点取值
//otherfun[‘fun3‘}(response);//也可以用字符串的方式取值
//-------用字符串调用对应的函数---
funname = ‘fun3‘;
otherfun[funname](response);
response.end(‘ ‘);
}).listen(8000);
console.log(‘Server running at http://127.0.0.1:8000/‘);
otherfun.js
module.exports = { //支持多个函数
fun2:function(res){
console.log("我是fun2");
res.write("你好,我是fun2");
},
fun3:function(res){
console.log("我是fun3");
res.write("你好,我是fun3");
}
}
/*function fun2(res){
console.log("fun2");
res.write("你好,我是fun2");
}
module.exports = fun2; //只支持一个函数 */