分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

node.js hello world和函数调用

发布时间:2023-09-06 01:30责任编辑:蔡小小关键词:js

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; ???//只支持一个函数 ?*/

  

node.js hello world和函数调用

原文地址:http://www.cnblogs.com/yin-dt/p/8025386.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved