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与Mysql的交互示例代码
Aug 18 NodeJs
Windows 系统下设置Nodejs NPM全局路径
Apr 26 NodeJs
Nodejs实现短信验证码功能
Feb 09 NodeJs
实例分析nodejs模块xml2js解析xml过程中遇到的坑
Mar 18 NodeJs
nodejs利用ajax实现网页无刷新上传图片实例代码
Jun 06 NodeJs
nodejs+mongodb+vue前后台配置ueditor的示例代码
Jan 02 NodeJs
对mac下nodejs 更新到最新版本的最新方法(推荐)
May 17 NodeJs
nodejs中用npm初始化来创建package.json的实例讲解
Oct 10 NodeJs
详解nodejs 开发企业微信第三方应用入门教程
Mar 12 NodeJs
nodejs微信开发之自动回复的实现
Mar 17 NodeJs
nodejs的安装使用与npm的介绍
Sep 11 NodeJs
在NodeJs中使用node-schedule增加定时器任务的方法
Jun 08 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
星际争霸 Starcraft 编年史
2020/03/14 星际争霸
PHILIPS L4X25T电路分析和打理
2021/03/02 无线电
强烈推荐:php.ini中文版(1)
2006/10/09 PHP
php,ajax实现分页
2008/03/27 PHP
使用bcompiler对PHP文件进行加密的代码
2010/08/29 PHP
php使用GeoIP库实例
2014/06/27 PHP
php ucwords() 函数将字符串中每个单词的首字符转换为大写(实现代码)
2016/05/12 PHP
PHP实现基于栈的后缀表达式求值功能
2017/11/10 PHP
PHP支付宝当面付2.0代码
2018/12/21 PHP
PHP重载基础知识回顾
2020/09/10 PHP
js 操作select相关方法函数
2009/12/06 Javascript
js 巧妙去除数组中的重复项
2010/01/25 Javascript
js动态改变select选择变更option的index值示例
2014/07/10 Javascript
php,js,css字符串截取的办法集锦
2014/09/26 Javascript
JavaScript设计模式之原型模式分析【ES5与ES6】
2018/07/26 Javascript
JS尾递归的实现方法及代码优化技巧
2019/01/19 Javascript
vue组件开发props验证的实现
2019/02/12 Javascript
qrcode生成二维码微信长按无法识别问题的解决
2019/04/04 Javascript
JavaScript中遍历的十种方法总结
2020/12/15 Javascript
[02:41]DOTA2英雄基础教程 冥魂大帝
2014/01/16 DOTA
Python中isnumeric()方法的使用简介
2015/05/19 Python
VScode编写第一个Python程序HelloWorld步骤
2018/04/06 Python
Python Dataframe 指定多列去重、求差集的方法
2018/07/10 Python
Python函数参数匹配模型通用规则keyword-only参数详解
2019/06/10 Python
利用python下载scihub成文献为PDF操作
2020/07/09 Python
Python中全局变量和局部变量的理解与区别
2021/02/07 Python
kmart凯马特官网:美国最大的打折零售商和全球最大的批发商之一
2016/11/17 全球购物
英格兰橄榄球商店:England Rugby Store
2016/12/17 全球购物
Happy Socks英国官网:购买五颜六色的袜子
2020/11/03 全球购物
2019年c语言经典面试题目
2016/08/17 面试题
linux面试题参考答案(9)
2016/01/29 面试题
绿色环保演讲稿
2014/05/10 职场文书
2014年体育教师工作总结
2014/12/03 职场文书
公安纪律作风整顿心得体会
2016/01/23 职场文书
《这片土地是神圣的》教学反思
2016/02/16 职场文书
2019教师的学习计划
2019/06/25 职场文书