我正在创建一个在Windows上使用node.js的本地应用。我们的想法是观察特定文件,并在文件发生变化时将内容发送到浏览器。
现在,为了测试,我只是从控制台查看文件中的fs.watch。我注意到,对我正在观看的文件进行一次更改会为控制台创建双输出。
这是服务器:
var fs, http, io, server;
fs = require('fs');
http = require('http');
server = http.createServer(function(req, res) {
return fs.readFile("" + __dirname + "/socket.io.demo.html", function(err, data) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
return res.end(data, 'utf8');
});
});
server.listen(1337);
fs.watch('/', function (event, filename) {
console.log('event is: ' + event);
if ('test.txt') {
console.log('filename provided: ' + filename);
} else {
console.log('filename not provided');
}
});
io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
socket.on('publish', function(message) {
return io.sockets.send(message);
});
socket.on('broadcast', function(message) {
return socket.broadcast.send(message);
});
return socket.on('whisper', function(message) {
return socket.broadcast.emit('secret', message);
});
});
这是html:
<!doctype html>
<html>
<head>
<title>Socket.IO demo</title>
</head>
<body>
<h1>Socket.IO demo</h1>
<input type="text" autofocus="autofocus" />
<button type="button">publish</button>
<button type="button">broadcast</button>
<button type="button">whisper</button>
<p>Status: <span id="status">Undefined</span></p>
<ol id="messages"></ol>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script>
<script type="text/coffeescript">
jQuery ($) ->
$status = $ '#status'
socket = io.connect()
socket.on 'connect', ->
$status.text 'Connected'
socket.on 'disconnect', ->
$status.text 'Disconnected'
socket.on 'reconnecting', (seconds) ->
$status.text "Reconnecting in #{seconds} seconds"
socket.on 'reconnect', ->
$status.text 'Reconnected'
socket.on 'reconnect_failed', ->
$status.text 'Failed to reconnect'
socket.on 'message', (message) ->
$('<li>').text(message).appendTo $('#messages')
socket.on 'secret', (message) ->
console.log message
$input = $ 'input'
$('button').click ->
socket.emit $(this).text(), $input.val()
$input.val('').focus()
</script>
</body>
</html>
有关为什么fs.watch在控制台中创建双输出的想法?
答案 0 :(得分:4)
看起来像Node错误。 https://github.com/joyent/node/issues/2126
作为临时解决方案,您可以考虑使用setTimeout来平滑事件。