According to Javascript; the semicolon after a statement (for example a function), is optional. However, it’s much better to end your line with a semicolon. A validator like JSLint for example, will throw a warning, even though the browser won’t [...]
Read More...The example below can be easily replaced with Node Connect. Just with a few lines. app.js
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
var http = require('http'); var path = require('path'); var fs = require('fs'); var extensions = { ".html" : 'text/html', ".css" : 'text/css', ".js" : 'application/javascript', ".json" : 'application/javascript', ".png" : 'images/png', ".gif" : 'images/gif', ".jpg" : 'images/jpeg' } http.createServer(function(req, res){ var filename = path.basename(req.url) || 'index.html', ext = path.extname(filename), dir = path.dirname(req.url).substring(1), localPath = __dirname + "/views/"; //console.log(localPath); if(extensions[ext]){ localPath += (dir ? dir + "/" : "") + filename; path.exists(localPath, function(exists){ if(exists){ getFile(localPath, extensions[ext], res) } else { res.writeHead(404); res.end(); } }); } }).listen(8000, '127.0.0.1'); getFile = function(localPath, mimeType, res){ fs.readFile(localPath, function(err, contents){ if(!err){ res.writeHead(200, { "Content-Type" : mimeType, "Content-Length" : contents.length }); res.end(contents); } else { res.writeHead(500); res.end(); } }); |
Now install Connect:
|
1 |
$ sudo npm install connect |
app.js
|
1 2 |
var connect = require("connect"); connect().use(connect.static(__dirname + "/views")).listen(8000); |
See the example below for an easy Hello World example with Node.js. Create a Node.JS server and serve a hardcoded response, with content-type: “text/html”. And listen to localhost:8000 in your browser to see the result. In your project folder create [...]
Read More...When you are sick and tired of restarting your node app in the terminal (CTRL+C) on every code change you make then you can automate this process. Actually it’s really simple. Install Nodemon via the package manager.
|
1 |
$ sudo npm install nodemon -p |
When you [...]
Read More...