发布于 2017-04-27 13:30:55 | 61 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Node.js教程,程序狗速度看过来!

Node.js 服务器端的JavaScript

Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台, 用来方便地搭建快速的 易于扩展的网络应用· Node.js 借助事件驱动, 非阻塞I/O 模型变得轻量和高效, 非常适合 运行在分布式设备 的 数据密集型 的实时应用


这篇文章主要为大家详细介绍了nodejs个人博客开发的入口文件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文为大家分享了nodejs个人博客开发的入口文件,具体内容如下

错误处理中间件

定义错误处理中间件必须使用4个参数,否则会被作为普通中间件


/*错误处理器*/
application.use(function(err,req,res,next){
 console.error(err.stack);
 res.status(500).send("代码出错了,错误信息:<br/>"+err.stack);
});
/*404*/
application.use(function(req,res,next){
 res.status(404).send("404页面被火星人挖走了");
});

创建文件结构

公共文件夹(common),控制器文件夹(controller),模型文件夹(model),视图文件夹(view),静态资源文件夹(static)

定义配置文件和函数文件并载入

配置文件common/config.js


/**
* 公共配置文件
*/
module.exports={
 DB_HOST:'localhost',
 DB_NAME:'blog',
 DB_USER:'root',
 DB_PASS:'root',
 DB_PRE:'',
 APP_PORT:'8888'
};

函数文件common/functions.js


/**
* 公共函数文件
*/
module.exports={
 /*模拟php的date()函数*/
 phpDate:function(formatStr,time){
  var paramModel='ymdhis';
  if(!formatStr) formatStr="y-m-d h:i:s";
  
  if(time){
   myDateTime=new Date(time*1000);
  }else{
   myDateTime=new Date();
  }
  var strTimeArr=[
   myDateTime.getFullYear().toString(),
   (myDateTime.getMonth()+1).toString(),
   myDateTime.getDate().toString(),
   myDateTime.getHours().toString(),
   myDateTime.getMinutes().toString(),
   myDateTime.getSeconds().toString(),
  ];
  for(var i=0;i<strTimeArr.length; i++){
   formatStr=formatStr.replace(paramModel.charAt(i), strTimeArr[i]);     
  }
  return formatStr;
 }

};

载入公共文件,定义资源文件


/*载入公共文件,定义资源文件*/
global.C=require("./common/config");
global.F=require("./common/functions"); 
application.use(express.static('public'));

路由级中间件

控制器分为两组home和admin


/*路由级中间件*/
application.use('/',require('./controller/home/index'));
application.use('/admin',require('./controller/admin/index'));

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持phperz。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务