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中自定义事件实例
Jun 20 NodeJs
在NodeJS中启用ECMAScript 6小结(windos以及Linux)
Jul 15 NodeJs
nodejs的10个性能优化技巧
Jul 15 NodeJs
详解nodejs 文本操作模块-fs模块(二)
Dec 22 NodeJs
nodejs入门教程四:URL相关模块用法分析
Apr 24 NodeJs
nodejs 日志模块winston的使用方法
May 02 NodeJs
nodejs 简单实现动态html的方法
May 12 NodeJs
nodeJs爬虫的技术点总结
May 13 NodeJs
Linux Centos7.2下安装nodejs&npm配置全局路径的教程
May 15 NodeJs
nodejs中用npm初始化来创建package.json的实例讲解
Oct 10 NodeJs
NodeJS http模块用法示例【创建web服务器/客户端】
Nov 05 NodeJs
nodejs nedb 封装库与使用方法示例
Feb 06 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
Windows 下的 PHP-PEAR 安装方法
2010/11/20 PHP
[原创]PHP获取数组表示的路径方法分析【数组转字符串】
2017/09/01 PHP
Laravel实现通过blade模板引擎渲染视图
2019/10/25 PHP
PHP7新特性
2021/03/09 PHP
关于viewport,Ext.panel和Ext.form.panel的关系
2009/05/07 Javascript
jquery text,radio,checkbox,select操作实现代码
2009/07/09 Javascript
javascript获取当前日期时间及其它操作函数
2011/01/11 Javascript
js自定义事件代码说明
2011/01/31 Javascript
50款非常棒的 jQuery 插件分享
2012/03/29 Javascript
JavaScript中instanceof运算符的用法总结
2013/11/19 Javascript
jQuery满屏焦点图左右滚动特效代码分享
2015/09/07 Javascript
JS+Canvas绘制时钟效果
2020/08/20 Javascript
jQuery中的通配符选择器使用总结
2016/05/30 Javascript
Bootstrap开发实战之响应式轮播图
2016/06/02 Javascript
js实现动态创建的元素绑定事件
2016/07/19 Javascript
node.js+jQuery实现用户登录注册AJAX交互
2017/04/28 jQuery
前端js中的事件循环eventloop机制详解
2019/05/15 Javascript
vue实现评论列表功能
2019/10/25 Javascript
[02:36]DOTA2亚洲邀请赛小组赛精彩集锦:奇迹哥卡尔秀翻全场
2017/03/28 DOTA
python单例模式实例分析
2015/04/08 Python
Python使用filetype精确判断文件类型
2017/07/02 Python
Python随机生成手机号、数字的方法详解
2017/07/21 Python
python如何对实例属性进行类型检查
2018/03/20 Python
教你使用python画一朵花送女朋友
2018/03/29 Python
python逐行读写txt文件的实例讲解
2018/04/03 Python
Python爬虫设置代理IP(图文)
2018/12/23 Python
python集合是否可变总结
2019/06/20 Python
python中时间、日期、时间戳的转换的实现方法
2019/07/06 Python
python 修改本地网络配置的方法
2019/08/14 Python
python 使用while写猜年龄小游戏过程解析
2019/10/07 Python
Python Django框架防御CSRF攻击的方法分析
2019/10/18 Python
Python类中的装饰器在当前类中的声明与调用详解
2020/04/15 Python
2015元旦晚会主持词(开场白+结束语)
2014/12/14 职场文书
vue首次渲染全过程
2021/04/21 Vue.js
pytorch 带batch的tensor类型图像显示操作
2021/05/20 Python
Mysql分库分表之后主键处理的几种方法
2022/02/15 MySQL