node.js编程之函数调用
2017-01-04编程大全
入门编程:打印hello world创建一个js文件,该文件名为:n1_hello.js 在该文件目录打开cmd窗口,输入:node n1_hello.js执行操作;窗口立即打印出"server running at http://127.0.0.1:8000/",其中访问前台浏览器
入门编程:打印hello world
创建一个js文件,该文件名为:n1_hello.js 在该文件目录打开cmd窗口,输入:node n1_hello.js执行操作;窗口立即打印出"server running at http://127.0.0.1:8000/",其中访问前台浏览器(http://localhost:8000)打印出“hello world结束”,同时cmd窗口在打印出“访问”,刷新一次打印一次。
var http = require('http');
http.createServer(function (request,response){//创建一个http服务
response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'})//http协议头
if(request.url!="/favicon.ico"){//清除第二次访问
console.log('访问');//每当在前台刷新时,就会在cmd命令窗口生成一个“访问”
response.write('hello world');
response.end('结束');//http协议尾,没有会一直转
}
}).listen(8000);//访问公网,改成80
console.log("server running at http://127.0.0.1:8000/");第一种:本地js函数调用
var http = require('http');
http.createServer(function (request,response){//创建一个http服务
response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'})//http协议头
if(request.url!="/favicon.ico"){//清除第二次访问
fun1(response);
response.end('');//http协议尾,没有会一直转
}
}).listen(8000);//访问公网,改成80
console.log("server running at http://127.0.0.1:8000/");
function fun1(res){//第一种:调用本页的js函数
console.log("fun1");
res.write("我是function1");
}第二种:1.1其他目录函数的调用,单个函数的调用
var http = require('http');
var otherfun = require("./models/otherfun");//引入其他的js文件
http.createServer(function (request,response){//创建一个http服务
response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'})//http协议头
if(request.url!="/favicon.ico"){//清除第二次访问
otherfun(response);//不能用fun2作为名字,otherfun其实就是fun2
response.end('');//http协议尾,没有会一直转
}
}).listen(8000);//访问公网,改成80
console.log("server running at http://127.0.0.1:8000/");
其他目录js写法
function fun2(res){
console.log("我是fun2");
res.write("你好,我是fun2");
}
module.exports = fun2; //只支持一个函数第二种:1.2其他目录函数的调用,多个函数的调用
var http = require('http');
var otherfun = require("./models/otherfun");//引入其他的js文件
http.createServer(function (request,response){//创建一个http服务
response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'})//http协议头
if(request.url!="/favicon.ico"){//清除第二次访问
otherfun.fun2(response);//不能用fun2作为名字,otherfun其实就是fun2
otherfun.fun3(response);//不能用fun3作为名字,otherfun其实就是fun3
funname='fun2';
//otherfun[funname](response);//不能用fun2作为名字,otherfun其实就是fun2
///otherfun['fun3'](response);//不能用fun3作为名字,otherfun其实就是fun3
response.end('');//http协议尾,没有会一直转
}
}).listen(8000);//访问公网,改成80
console.log("server running at http://127.0.0.1:8000/");
其他目录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; //只支持一个函数
*/ 很赞哦! ()
