先学习一个nodejs库
npm install request --save-dev
有了这个库,我们可以在nodejs里面很方便的实现类似curl功能。
1.先来试一下这个request,写一个1.js,代码如下:
var request = require('request');
request.get('http://localhost/myphp/news.php',function(error,response,body){
if(!error && response.statusCode == 200){
console.log(body);
}
});
执行 node 1.js
后终端输出:
http://localhost/myphp/news.php 代码如下:
<?php
$news['id'] = 123;
$news['title'] = '今天的气温到达了38℃';
$news['content'] = '天气太热啦,天气太热啦,天气太热啦,天气太热啦';
header("Access-Control-Allow-Origin:http://localhost");
header("Content-type: application/json");
// json_encode 加JSON_UNESCAPED_UNICODE参数 中文不转码.在PHP5.4可用
die(json_encode($news));
试验通过,证明nodejs这个request类库可用。
2.封装一个自己的类库,专门用来加载新闻数据
node_modules/myLib/index.js
下:
var request = require('request');
exports.loadNews = function(doSomething){
request.get('http://localhost/myphp/news.php',function(error,response,body){
if(!error && response.statusCode == 200){
doSomething(body);
}
});
}
这样就可用在其他地方引入这个类库,比如我们在2.js下:
var myLib = require('myLib');
myLib.loadNews(function(data){
console.log(data);
});
然后终端执行 node 2.js
发现成功打印新闻数据啦。
3.最后我们终于可用进入主题来看看,gulp里是怎么做的
编辑gulpfile.js:
var gp = require('gulp');
var gulp_tpl = require('gulp-template');
gp.task('news',function(){
var myLib = require('myLib');
myLib.loadNews(function(data){
gp.src(['index.html'])
.pipe(gulp_tpl(JSON.parse(data)))
.pipe(gp.dest('./build/html'));
});
})
并且修改项目根目录下的index.html模板文件:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<span>ID:<%=id%></span>
<h1>新闻标题:<%=title%></h1>
<hr/>
<p><%=content%></p>
</body>
</html>
然后在终端执行gulp任务:gulp news
, 最后果然在/build/html
目录下多了一个index.html,内容就是我们的新闻数据
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<span>ID:123</span>
<h1>新闻标题:今天的气温到达了38℃</h1>
<hr/>
<p>天气太热啦,天气太热啦,天气太热啦,天气太热啦</p>
</body>
</html>
4.因为我们读取的html模板名是index.html,最后生成的也是index.html,如果我们想要最后生成不同的文件名,怎么办呢?
我们需要现在安装一个gulp-rename插件:
npm install gulp-rename --save-dev
然后gulpfile.js这样写:
var gp = require('gulp');
var gulp_tpl = require('gulp-template');
var gulp_rename = require('gulp-rename');
gp.task('news',function(){
var myLib = require('myLib');
myLib.loadNews(function(data){
var news = JSON.parse(data);
gp.src(['index.html'])
.pipe(gulp_tpl(news))
.pipe(gulp_rename(news.id+'.html'))
.pipe(gp.dest('./build/html'));
});
})
这样执行gulp news命令后,build/html目录下就生成了我们新闻123.html。(123就是我们新闻id)