-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
84 lines (71 loc) · 2.32 KB
/
Copy pathsocket.js
File metadata and controls
84 lines (71 loc) · 2.32 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* socket.js - comunicacao bidirecional
*/
/*jslint node : true, continue : true,
devel : true, indent : 2, maxerr : 50,
newcap : true, nomen : true, plusplus : true,
regexp : true, sloppy : true, vars : false,
white : true
*/
/*global */
// ------------ BEGIN MODULE SCOPE VARIABLES --------------
'use strict';
var
countUp,
setWatch,
http = require ( 'http' ),
express = require( 'express' ),
socketIo = require( 'socket.io' ),
fsHandle = require('fs' ),
app = express(),
server = http.createServer( app ),
io = socketIo.listen(server),
countIdx = 0,
watchMap = {}
;
// ------------- END MODULE SCOPE VARIABLES ---------------
// --------------- BEGIN UTILITY METHODS ------------------
countUp = function () {
countIdx++;
console.log( countIdx );
io.sockets.send( countIdx );
};
setWatch = function ( url_path, file_type ) {
console.log( 'setWatch em ' + url_path );
if ( ! watchMap [url_path ] ) {
console.log( 'definido watch em ' + url_path );
fsHandle.watchFile(
url_path.slice(1),
function ( current, previous ) {
console.log( 'ficheiro acessado' );
if ( current.mtime !== previous.mtime ) {
console.log( 'ficheiro alterado ' );
io.sockets.emit( file_type, url_path );
}
}
);
watchMap[ url_path ] = true;
}
};
// ---------------- END UTILITY METHODS -------------------
// ------------- BEGIN SERVER CONFIGURATION ---------------
app.use( function ( request, response, next ){
if ( request.url.indexOf( '/js/' ) >= 0 ) {
setWatch( request.url, 'script' );
} else if ( request.url.indexOf( '/css/' ) >= 0) {
setWatch( request.url, 'stylesheet' );
}
next();
});
app.use( express.static( __dirname + '/' ) );
app.get( '/', function ( request, response ) {
response.redirect( '/socket.html' );
});
// -------------- END SERVER CONFIGURATION ----------------
// ----------------- BEGIN START SERVER -------------------
server.listen( 3000 );
console.log(
'Express server listening on port %d in %s mode',
server.address().port, app.settings.env
);
// ------------------ END START SERVER --------------------