Can Node.js apps have static URLs?
So I've been hearing a lot about Node.js and javascript web apps in general. The examples that I know of tend to function more like native apps than web apps in that static URLs aren't available. Their doesn't seem to be dedicated pages that one can link to.
My question is...is it smart to build a web app in node.js if the presence of static pages (URLs) is essential to that app (for example; think of how one needs to link to a tweet or an ebay listing or a wordpress post).
Thanks!
Ed开发者_运维技巧die
This answer is for static pages and files since static urls is not really a problem with node.js, and it's covered here at the express js guide.
Using only node.js without any framework is a pretty bad idea if you're going to build a webapp. However, there are lots of good webframeworks for node.js that makes life a lot easier. If you've got NPM installed they are really easy to include too.
I've only got experience with express.js but it makes it really easy to create webapps if you've got any previous experience with any MVC type web-framework.
From my experience it's true that there is no way to serve static pages built in to node.js. However, building a controller that can serve static pages it really simple.
Here is an example using express.js.
server.js
...
app.get('/content/*', controllers.content.getfile);
...
This creates a route that captures every url going to the content
directory and directs it to the action getfile in the content controller i.e. www.yourdomain.com/content/style.css
controllers.js
...
exports.content = {
getfile : function(req,res){
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri);
path.exists(filename, function(exists){
if(!exists){
res.writeHead(404, {"Content-Type" : "text/plain"});
res.write("Content not found");
res.end();
return;
}
fs.readFile(filename, "binary", function(err, file){
res.writeHead(200, {'Content-Type' : mime.lookup(filename) });
res.write(file, "binary");
res.end();
});
});
}
}
...
This action getfile in the content controller looks for the file specified in the URL in the content directory and serves it up to the client. It requires
the mime library that you can get with NPM.
This enables the use of static files in the /content/ folder. If you'd like to you could make the route catch every non caught URL and look for a static file from the route up. However you'd have to set up some kind of filter so that you can't just access server.js file.
精彩评论