I'd like to see if it's possible to make an CLI app that simply displays the date and time with node.js. So far I've only figured out how to send the date开发者_开发百科 and time over HTTP. Here's what I have:
var sys = require('sys');
var http = require('http');
var s = http.createServer(function(req, res) {
var now = require('datetime');
now = new Date();
res.writeHead(200, { 'content-type': 'text/plain' });
setInterval(function() {
res.write(now.toString());
res.write("\n");
now = new Date();
}, 1000);
});
s.listen(8888);
There are a few problems with this. Nothing is being printed to the command line and the in the browser the datetime isn't refreshed, it is printed under the previous printout. How can I get this to print out on the command line, and how can I get this to clear the previously printed text?
I am using node.js 0.5.5.
Use console.log
to output things to the console.
Use Now.js to update the client.
Use console.log('\033[2J');
to clear the logged output.
Also check out https://github.com/joyent/node/wiki/modules#wiki-debugging for nice console extensions, they make things easier.
You can print to the command line in Node.js with console.log()
. So do:
console.log(new Date());
Right now your Node.js server only responds to each request. It doesn't have a way to push new info out to the client without the client making a request. An easy way to get that to work is with some client-side javascript.
$(function() {
// Update every 5 seconds
setInterval(function() {
$.ajax({
url:"http://localhost:8888",
success: function(data) { $("#time").text(data); }
});
}, 5000);
});
This assumes you have an HTML element with an ID of time somewhere on the page.
If you just want to print stuff out to the console, you can replace your entire script with a call to setInterval
like this:
setInterval(function() { console.log(new Date()); }, 5000);
精彩评论