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 相关文章推荐
使用upstart把nodejs应用封装为系统服务实例
Jun 01 NodeJs
详解Nodejs的timers模块
Dec 22 NodeJs
简单实现nodejs上传功能
Jan 14 NodeJs
详解nodejs中exports和module.exports的区别
Feb 17 NodeJs
nodejs中使用HTTP分块响应和定时器示例代码
Mar 19 NodeJs
nodejs入门教程三:调用内部和外部方法示例
Apr 24 NodeJs
NodeJs模拟登陆正方教务
Apr 28 NodeJs
nodeJS实现路由功能实例代码
Jun 08 NodeJs
nodejs使用redis作为缓存介质实现的封装缓存类示例
Feb 07 NodeJs
webstorm中配置nodejs环境及npm的实例
May 15 NodeJs
Nodejs中获取当前函数被调用的行数及文件名详解
Dec 12 NodeJs
nodejs简单抓包工具使用详解
Aug 23 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操作redis中的hash和zset类型数据的方法和代码例子
2014/07/05 PHP
PHP的Yii框架中Model模型的学习教程
2016/03/29 PHP
PHP实现路由映射到指定控制器
2016/08/13 PHP
thinkPHP框架实现生成条形码的方法示例
2018/06/06 PHP
关于laravel 日志写入失败问题汇总
2019/10/17 PHP
JavaScript获取GridView中用户点击控件的行号,列号
2009/04/14 Javascript
jQuery live( type, fn ) 委派事件实现
2009/10/11 Javascript
NodeJS 模块开发及发布详解分享
2012/03/07 NodeJs
基于jquery实现一张图片点击鼠标放大再点缩小
2013/09/29 Javascript
基于socket.io和node.js搭建即时通信系统
2014/07/30 Javascript
AngularJS入门教程之ng-checked 指令详解
2016/08/01 Javascript
js中的eval()函数把含有转义字符的字符串转换成Object对象的方法
2016/12/02 Javascript
Bootstrap源码解读下拉菜单(4)
2016/12/23 Javascript
简单谈谈Javascript函数中的arguments
2017/02/09 Javascript
20个必会的JavaScript面试题(小结)
2019/07/02 Javascript
微信小程序换肤功能实现代码(思路详解)
2020/08/25 Javascript
用python + hadoop streaming 分布式编程(一) -- 原理介绍,样例程序与本地调试
2014/07/14 Python
Python中__call__用法实例
2014/08/29 Python
Python中处理字符串之islower()方法的使用简介
2015/05/19 Python
Python简单调用MySQL存储过程并获得返回值的方法
2015/07/20 Python
Python3中使用urllib的方法详解(header,代理,超时,认证,异常处理)
2016/09/21 Python
Python中查看文件名和文件路径
2017/03/31 Python
python机器学习实战之最近邻kNN分类器
2017/12/20 Python
Python退火算法在高次方程的应用
2018/07/26 Python
浅谈解除装饰器作用(python3新增)
2018/10/15 Python
Django如何使用asyncio协程和ThreadPoolExecutor多线程
2020/10/12 Python
python和C++共享内存传输图像的示例
2020/10/27 Python
加拿大领先的牛仔零售商:Bluenotes
2018/01/22 全球购物
Whittard官方海外旗舰店:英国百年茶叶品牌
2018/02/22 全球购物
优秀党员主要事迹
2014/01/19 职场文书
财务部总监岗位职责
2014/03/12 职场文书
师范生自荐信模板
2014/05/28 职场文书
写字楼租赁意向书
2014/07/30 职场文书
就业推荐表导师评语
2014/12/31 职场文书
幼儿园教师节活动总结
2015/03/23 职场文书
帝企鹅日记观后感
2015/06/10 职场文书