DateFormat in #nodejs

Adding some DateFormat functions to Node ended up being quite simple

view plain print about
1$ mkdir testDateFormat && testDateFormat
2$ npm install dateformat
3$ subl app.js

For this I installed it locally, you can always add -g to add it locally. The final line opens up a new file called app.js in Sublime Text 2 for me. In there we are going to create a simple web app (cause thats what you do with Node.js apparently) and quickly return the date to a Hello World program.

view plain print about
1var http = require('http');
2// requre the dateFormat
3var dateFormat = require('dateFormat')
4
5// Create a function to return the current Date and Time
6function getDateTime(){
7    var now = new Date();
8    return dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
9}
10
11
12http.createServer(function (req, res) {
13
14    // Add some output to the browser including date and time
15    var textResponse = "Hello world @ " + getDateTime() + '\n\nCheck out more at https://github.com/felixge/node-dateformat';
16    
17    // output to the browser
18    res.writeHead(200, {'Content-Type': 'text/plain'});
19    res.end( textResponse );
20    
21}).listen(1337, "127.0.0.1");
22
23// Tell the console when the server was started
24console.log('Server running on http://127.0.0.1:1337/ Started @ ' + getDateTime());

Once you've saved app.js call $ node app.js from the Terminal and go to http://localhost:1337.

This only scratches the service of what it can do, check out more at github.com/felixge/node-dateformat

Posted: 21-Dec-2011

View: 1336

Permalink: here

Comments