nodejs基础应用


Posted in NodeJs onFebruary 03, 2017

一、第一个nodejs应用

n1_hello.js

console.log('hello word!');

在命令行cmd中执行该文件(在该文件处打开命令行):

node n1_hello.js

在命令行cmd返回结果:

hello word!

二、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路由初步

主程序n4_rout.js:

var http = require('http');
//引入url模块
var url = require('url');
http.createServer(function (request, response) {
 response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'});
 if(request.url!=='/favicon.ico'){
  var pathname = url.parse(request.url).pathname;
  pathname=pathname.replace(/\//,'');//替换掉前面的/
  console.log(pathname);
  response.end('');
 }
}).listen(8000);
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8000/');

在命令行cmd中执行该文件,在访问:http://localhost:8000/,在此输入路由地址,如下图,并观察命令行。

nodejs基础应用

五、nodejs读取文件

主程序:

var http = require('http');
var optfile=require('./models/optfile');//导入文件
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'){//清除第2次访问
  optfile.readfileSync('./views/login.html');//同步调用读取文件readfileSync()方法
  //optfile.readfile('./views/login.html',response);//异步步调用读取文件readfile()方法
  response.end('ok!!!!!');//todo 不写没有协议尾
  console.log('主程序执行完毕!');
 }
}).listen(8000);
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8000/');

optfile.js中:

var fs=require('fs');//Node 导入文件系统模块(fs)语法 导入fs操作文件的类
module.exports={
 readfileSync:function(path){
  // 同步读取
  var data = fs.readFileSync(path,'utf-8');//以中文读取同步文件路径path
  console.log("同步方法执行完毕。");
 },
 readfile:function(path){
  // 异步读取
  fs.readFile(path,function (err, data) {
   if (err) {
    console.error(err);
   }else{
    console.log("异步读取: " + data.toString());
   }
  });
  console.log("异步方法执行完毕。");
 },
}

结果:命令行cmd中

(1)同步读取文件时:

   nodejs基础应用

(2)异步读取文件时:(常用)

   nodejs基础应用

   网页中:均为:

nodejs基础应用

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持三水点靠木!

NodeJs 相关文章推荐
跟我学Nodejs(三)--- Node.js模块
May 25 NodeJs
使用forever管理nodejs应用教程
Jun 03 NodeJs
nodejs获取微信小程序带参数二维码实现代码
Apr 12 NodeJs
nodejs socket服务端和客户端简单通信功能
Sep 14 NodeJs
nodejs中安装ghost出错的原因及解决方法
Oct 23 NodeJs
详解IWinter 一个路由转控制器的 Nodejs 库
Nov 15 NodeJs
详解Nodejs内存治理
May 13 NodeJs
webstorm中配置nodejs环境及npm的实例
May 15 NodeJs
nodejs用gulp管理前端文件方法
Jun 24 NodeJs
nodejs中函数的调用实例详解
Oct 31 NodeJs
用Electron写个带界面的nodejs爬虫的实现方法
Jan 29 NodeJs
详解NodeJS Https HSM双向认证实现
Mar 12 NodeJs
nodejs基础知识
Feb 03 #NodeJs
windows 下安装nodejs 环境变量设置
Feb 02 #NodeJs
图片上传之FileAPI与NodeJs
Jan 24 #NodeJs
初探nodeJS
Jan 24 #NodeJs
进阶之初探nodeJS
Jan 24 #NodeJs
用nodejs搭建websocket服务器
Jan 23 #NodeJs
NodeJS遍历文件生产文件列表功能示例
Jan 22 #NodeJs
You might like
PHP与SQL注入攻击[一]
2007/04/17 PHP
thinkPHP下ueditor的使用方法详解
2015/12/26 PHP
PHP基于phpqrcode类生成二维码的方法示例详解
2020/08/07 PHP
JavaScript 获取事件对象的注意点
2009/07/29 Javascript
js word表格动态添加代码
2010/06/07 Javascript
有趣的JavaScript数组长度问题代码说明
2011/01/20 Javascript
jquery 多行文本框(textarea)高度变化
2013/07/03 Javascript
escape编码与unescape解码汉字出现乱码的解决方法
2014/07/02 Javascript
理解JavaScript中Promise的使用
2016/01/18 Javascript
Atitit.js的键盘按键事件捆绑and事件调度
2016/04/01 Javascript
js html css实现复选框全选与反选
2016/10/09 Javascript
BootStrap实现响应式布局导航栏折叠隐藏效果(在小屏幕、手机屏幕浏览时自动折叠隐藏)
2016/11/30 Javascript
javascript简单链式调用案例分析
2017/05/10 Javascript
JavaScript设计模式之职责链模式应用示例
2018/08/07 Javascript
如何用RxJS实现Redux Form
2018/12/29 Javascript
vue+iview实现分页及查询功能
2020/11/17 Vue.js
[06:45]DOTA2-DPC中国联赛 正赛 Magma vs LBZS 选手采访
2021/03/11 DOTA
Python使用MD5加密字符串示例
2014/08/22 Python
Python模拟三级菜单效果
2017/09/11 Python
python读取目录下最新的文件夹方法
2018/12/24 Python
Django+python服务器部署与环境部署教程详解
2020/03/30 Python
如何使用PyCharm将代码上传到GitHub上(图文详解)
2020/04/27 Python
Python 下载Bing壁纸的示例
2020/09/29 Python
快速创建python 虚拟环境
2020/11/28 Python
使用豆瓣源来安装python中的第三方库方法
2021/01/26 Python
CSS3动画和HTML5新特性详解
2020/08/31 HTML / CSS
欧洲顶级的童装奢侈品购物网站:Bambini Fashion(面向全球)
2018/04/24 全球购物
结构和类有什么异同
2012/07/16 面试题
电气工程及其自动化专业求职信
2014/06/23 职场文书
班级学雷锋活动总结
2014/06/26 职场文书
人大代表选举标语
2014/10/07 职场文书
房产协议书范本
2014/10/18 职场文书
大学生助学金感谢信
2015/01/21 职场文书
杭州西湖英语导游词
2015/02/03 职场文书
学校捐款活动总结
2015/05/09 职场文书
儿子满月酒致辞
2015/07/29 职场文书