Express is a web framework for node.js, i.e. we can finally build a web server (easily). To install it, use
$ npm install --save expressThe --save adds the module to our dependency list. Here is a simple app to get us started:
var express = require('express');
var app = express();
app.get('/', function(request, response){
response.sendFile(__dirname + "/index.html");
});
app.listen(8080);
ejs
ejs is the template (templating?) package. By default it will look for templates under 'views' directory. Here is a more complicated example using ejs:
var request = require('request');
var url = require('url');
// route definition
app.get('/tweets/:username',function(req,response){
var username = req.params.username;
options = {
protocol: "http",
host: 'api.twitter.com',
pathname: '/1/statuses/user_timeline.json',
query: { screen_name: username, count: 10}
}
var twitterUrl = url.format(options);
//request(twitterUrl).pipe(response);
request(url, function(err,res,body) {
var tweets = JSON.parse(body);
response.locals = {tweets: tweets, name: username};
response.render('tweets.ejs');
});
where the template looks like
Tweets for @<%=name%>
-
<% tweets.forEach(function(tweet){ %>
- <%== tweet.text %> <% }); %>
curl -s http://localhost:8080/tweets/eallam
Here is another example, supposing that we are going to call Twitter's search API, e.g http://search.twitter.com/search.json?q=codeschool. It uses the 'request' module.
var req = require('request');
var url = require('url');
var experss = require('express');
var options = {
protocol: "http:",
host: "search.twitter.com",
pathname: '/search.json',
query: { q: "codeschool"}
};
var searchURL = url.format(options);
var app = express();
app.get('/',function(req,response){
request(searchURL).pipe(response);
}).listen(8080);
});
No comments:
Post a Comment