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读取memcache示例分享
Jan 02 NodeJs
Nodejs 发送Post请求功能(发短信验证码例子)
Feb 09 NodeJs
详解nodejs中的process进程
Mar 19 NodeJs
Ajax异步文件上传与NodeJS express服务端处理
Apr 01 NodeJs
nodejs个人博客开发第六步 数据分页
Apr 12 NodeJs
Nodejs搭建wss服务器教程
May 24 NodeJs
nodejs中art-template模板语法的引入及冲突解决方案
Nov 07 NodeJs
Nodejs把接收图片base64格式保存为文件存储到服务器上
Sep 26 NodeJs
nodejs npm错误Error:UNKNOWN:unknown error,mkdir 'D:\Develop\nodejs\node_global'at Error
Mar 02 NodeJs
nodejs dgram模块广播+组播的实现示例
Nov 04 NodeJs
nodejs使用socket5进行代理请求的实现
Feb 21 NodeJs
windows如何把已安装的nodejs高版本降级为低版本(图文教程)
Dec 14 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 伪造本地文件包含漏洞的代码
2011/11/03 PHP
php模板函数 正则实现代码
2012/10/15 PHP
利用phpExcel实现Excel数据的导入导出(全步骤详细解析)
2013/11/26 PHP
PHP连接MSSQL2008/2005数据库(SQLSRV)配置实例
2014/10/22 PHP
php从给定url获取文件扩展名的方法
2015/03/14 PHP
PHP小偷程序的设计与实现方法详解
2016/10/15 PHP
php中__toString()方法用法示例
2016/12/07 PHP
php实现session共享的实例方法
2019/09/19 PHP
节点的插入之append()和appendTo()的用法介绍
2014/01/13 Javascript
深入理解JS中的变量及作用域、undefined与null
2014/03/04 Javascript
HTML5 canvas 9绘制图片实例详解
2016/09/06 Javascript
HTML5 JS压缩图片并获取图片BASE64编码上传
2020/11/16 Javascript
jQuery使用Layer弹出层插件闪退问题
2016/12/22 Javascript
js实现返回顶部效果
2017/03/10 Javascript
基于JQuery和原生JavaScript实现网页定位导航特效
2017/04/03 jQuery
使用electron将vue-cli项目打包成exe的方法
2018/09/29 Javascript
vue项目环境变量配置的实现方法
2018/10/12 Javascript
JS复杂判断的更优雅写法代码详解
2018/11/07 Javascript
卸载vue2.0并升级vue_cli3.0的实例讲解
2020/02/16 Javascript
Linux-ubuntu16.04 Python3.5配置OpenCV3.2的方法
2018/04/02 Python
对python 各种删除文件失败的处理方式分享
2018/04/24 Python
用TensorFlow实现多类支持向量机的示例代码
2018/04/28 Python
python smtplib模块自动收发邮件功能(一)
2018/05/22 Python
对Tensorflow中的矩阵运算函数详解
2018/07/27 Python
pytorch 实现张量tensor,图片,CPU,GPU,数组等的转换
2020/01/13 Python
pycharm永久激活超详细教程
2020/10/29 Python
aden + anais英国官网:美国婴儿贴身用品品牌
2019/09/08 全球购物
一份Java笔试题
2012/02/21 面试题
一些高难度的SQL面试题
2016/11/29 面试题
租房合同协议书
2014/04/09 职场文书
《有趣的发现》教学反思
2014/04/15 职场文书
优秀教师演讲稿
2014/05/06 职场文书
立志成才演讲稿
2014/09/04 职场文书
迎新生欢迎词
2015/01/23 职场文书
解除劳动合同通知书范本
2015/04/16 职场文书
2019年亲子运动会口号
2019/10/11 职场文书