app.js(记得安装下面这些模块)
var express=require('express'); var path=require('path'); var port=process.env.PORT ||3000; var app=express(); var fs=require('fs'); app.set('views','./views/pages'); app.set('view engine','jade');
//设置网站的静态目录。<span style="font-family: Arial, Helvetica, sans-serif;">__dirname 是app.js (程序入口文件)所在的目录。因为图片都保存在photos文件夹下,所以设置静态路径。直接浏览localhost:3000/图片名 就对应该目录下的文件名。这就是express.static 的作用</span> app.use(express.static(path.join(__dirname,'/<span style="font-family: Arial, Helvetica, sans-serif;">photos</span><span style="font-family: Arial, Helvetica, sans-serif;">')) );</span> app.listen(port); console.log('started on port' + port ); app.get('/photos', function(req,res){ var files =fs.readdirSync('phtos') res.render('index',{ title:'study book' , imgs:files, description:'照片墙' }) })
app.get('*', function(req, res){ <span style="white-space:pre"> </span>res.render('404',{ <span style="white-space:pre"> </span> <span style="white-space:pre"> </span>}) }); //404页面head.jade(引用项目需要的js,css)
link(href="/bootstrap/dist/css/bootstrap.min.css" rel='stylesheet') script(src='/jquery/dist/jquery.min.js') script(src='/bootstrap/dist/js/bootstrap.min.js')
header.jade(页面头部模板)
.container .row .page-header h1 #{title} small 科幻片
layout.jade (相当于一个master,页面的公用部分)
doctype html head meta(charset='utf-8') title #{title} include ./includes/head body include ./includes/header block content
extends ../layout block content p #{description} each img in imgs img(src="/#{img}" style="width:140px;height:140px;margin:5px")
备注:jade的格式要注意,如果内容缩进不正确,会导致页面报错。(个人不喜欢这种方式,错不好查)