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中SSL服务的性能
Jul 15 NodeJs
nodejs中实现sleep功能实例
Mar 24 NodeJs
Nodejs 发送Post请求功能(发短信验证码例子)
Feb 09 NodeJs
基于nodejs 的多页面爬虫实例代码
May 31 NodeJs
NodeJs使用Mysql模块实现事务处理实例
May 31 NodeJs
nodejs 最新版安装npm 的使用详解
Jan 18 NodeJs
nodejs中Express与Koa2对比分析
Feb 06 NodeJs
Nodejs下使用gm圆形裁剪并合成图片的示例
Feb 22 NodeJs
nodejs实现连接mongodb数据库的方法示例
Mar 15 NodeJs
nodejs搭建本地服务器轻松解决跨域问题
Mar 21 NodeJs
nodejs中方法和模块用法示例
Dec 24 NodeJs
nodejs中内置模块fs,path常见的用法说明
Nov 07 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判断文件是否存在、是否可读、目录是否存在的代码
2012/10/03 PHP
设置php页面编码的两种方法示例介绍
2014/03/03 PHP
php将12小时制转换成24小时制的方法
2015/03/31 PHP
fckeditor上传文件按日期存放及重命名方法
2015/05/22 PHP
PHP设计模式之注册树模式分析
2018/01/26 PHP
thinkPHP5.0框架验证码调用及点击图片刷新简单实现方法
2018/09/07 PHP
PHP字符串与数组处理函数用法小结
2020/01/07 PHP
ExtJS下 Ext.Direct加载和提交过程排错小结
2013/04/02 Javascript
javascript静态页面传值的三种方法分享
2013/11/12 Javascript
Javascript 按位左移运算符使用介绍(
2014/02/04 Javascript
js实现鼠标悬停图片上时滚动文字说明的方法
2015/02/17 Javascript
手机图片预览插件photoswipe.js使用总结
2016/08/25 Javascript
jquery获取input type=text中的值的各种方式(总结)
2016/12/02 Javascript
浅谈Node.js:理解stream
2016/12/08 Javascript
Vuejs实现带样式的单文件组件新方法
2017/05/02 Javascript
vue-router3.0版本中 router.push 不能刷新页面的问题
2018/05/10 Javascript
JS精确判断数据类型代码实例
2019/12/18 Javascript
vue iview 隐藏Table组件里的某一列操作
2020/11/13 Javascript
python采集博客中上传的QQ截图文件
2014/07/18 Python
Python实现树的先序、中序、后序排序算法示例
2017/06/23 Python
基于python(urlparse)模板的使用方法总结
2017/10/13 Python
对Tensorflow中权值和feature map的可视化详解
2018/06/14 Python
Python SQL查询并生成json文件操作示例
2018/08/17 Python
浅谈python下含中文字符串正则表达式的编码问题
2018/12/07 Python
有关Tensorflow梯度下降常用的优化方法分享
2020/02/04 Python
利用HTML5中的Canvas绘制一张笑脸的教程
2015/05/07 HTML / CSS
视图的作用
2014/12/19 面试题
计算机数据库专业职业生涯规划书
2014/02/08 职场文书
毕业班联欢会主持词
2014/03/27 职场文书
2014年寒假社会实践活动心得体会
2014/04/07 职场文书
爱国主义教育活动总结
2014/05/07 职场文书
2014党支部对照检查材料思想汇报
2014/10/05 职场文书
基于CSS3画一个iPhone
2021/04/21 HTML / CSS
Python图像处理之图像拼接
2021/04/28 Python
星际争霸 Light vs Action 一场把教主看到鬼畜的比赛
2022/04/01 星际争霸
阿里云服务器(windows)手动部署FTP站点详细教程
2022/08/05 Servers