做了一个简单的示例,目的是记录环境配置以及这套框架的结构流程。
1.配置环境
默认nodejs已安装。
安装以下模块:express(nodejs框架),grunt(javascript task runner),grunt-contrib-watch(grunt live load插件),grunt-express-server(grunt启动express服务端插件)。
命令行中进入程序目录,依次输入以下命令:
npm install express 回车
npm install grunt 回车
npm install grunt-contrib-watch 回车
npm install grunt-express-server 回车
安装成功后,可以在程序目录中的node_modules文件夹里看到相应的模块文件夹:
2.配置grunt 任务
打开程序目录下的Gruntfile.js文件,注册express和watch任务。
express任务启动express服务器并且运行server.js文件。watch任务监视express任务以及live reload。代码如下:
module.exports = function(grunt) {//config projectgrunt.initConfig({watch: {options: {livereload: true,},express: {files: [ 'server.js' ],options: {spawn: false}}},//start express server and run server.jsexpress: {options: {// Override defaults here},dev: {options: {script: 'server.js'}}}});//enable pluginsgrunt.loadNpmTasks('grunt-express-server');grunt.loadNpmTasks('grunt-contrib-watch');//register taskgrunt.registerTask('default', ['express','watch']);
};
3. 主要文件
serve_data.js,server.js和index.html都在程序目录下。
index.html用angularjs resource向服务器上的‘/data’路径发起http请求。
在server.js中定义了路径‘/data’的行为是返回通过serve_data.js文件中的getData()方法获取的data变量。
index.html 的resource收到返回的data后,通过数据绑定{{data}}将其显示在页面上。
三个文件具体代码及注释如下:
index.html:
<!DOCTYPE html>
<html>
<head>
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<scriptsrc="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-resource.min.js"></script>
</head>
<body ng-app="myApp" ng-controller=MainCtrl><div>{{data}}</div><script>var myApp = angular.module('myApp', [ 'ngResource' ]);//define app factorymyApp.factory('DataFac', function($resource) {//request data from route '/data'return $resource('data');});//define app controllermyApp.controller('MainCtrl', function($scope, DataFac) {DataFac.get(function(response) {$scope.data = response;})});</script>
</body>
</html>
server.js:
//use express
var express = require('express');
var app = express();//require file serve_data.js to use its exported modules
var instance=require('./serve_data.js')
var data=instance.getData();//define route
app.get('/data',function(req,res){res.send(data);
});//serve static index.html as default
app.use(express.static(__dirname + '/'));//bind and listen for connections on the given host and port
app.listen(9001,function(){console.log('Server listening on',9001)
})
//export funtion getData
module.exports={getData:function(){//data can be fetched from a database or a file and so on. Here for simplicity,provide json data directlyvar data={"widget": {"debug": "on","window": {"title": "Sample Widget","name": "main_window","width": 500,"height": 500},"image": { "src": "Images/test.png","hOffset": 250,"vOffset": 250,"alignment": "center"},"text": {"data": "Click Here","size": 36,"style": "bold","name": "text1","hOffset": 250,"vOffset": 100,"alignment": "center"}}} ;return data;}
}
4.运行程序
在命令行中进入程序目录,输入grunt运行grunt任务。打开浏览器进入http://localhost:9001/ ,得到以下结果: