-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileserver.js
105 lines (81 loc) · 2.82 KB
/
fileserver.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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
var express = require( 'express' );
var form = require( 'connect-form' );
var mime = require( 'mime' );
var url = require( 'url' );
var fs = require( 'fs' );
var path = require( 'path' );
var app = express.createServer( form({ keepExtensions: true }) );
var io = require( 'socket.io' ).listen( app );
var clients = [];
documentRoot = "./public_html";
app.post( /upload\/$/, function( req, resp ) {
req.form.complete( function( err, fields, files ) {
if ( err ) {
return write500( resp, "failed to upload image" );
}
var src = files.image.path;
var safeFileName = files.image.name.replace(
/[^a-zA-Z0-9_\.-]/g, "_"
);
var dest = documentRoot + '/img/' + safeFileName;
console.log( safeFileName );
console.log( dest );
fs.rename( src, dest, function( err ) {
if ( err ) {
return write500( resp, "failed to upload image" );
}
io.sockets.emit( "update", { fileName : safeFileName } );
resp.writeHead( 200, { "Content-Type":"application/json" } )
resp.write( JSON.stringify( { "status":"complete" } ) );
resp.end();
});
});
});
// get static files
app.get( /.*/, function( req, resp ) {
console.log( 'requesting : ' + req.path );
fileName = __dirname + '/public_html' + req.path;
( function( file ) {
fs.stat( file, function( err, stats ) {
if ( err ) {
console.log( 'file not found' );
return write404( resp, req.path + ' not found' );
}
if ( stats.isDirectory() ) {
fs.readdir( file, function( err, files ) {
resp.writeHead( 200, {} )
resp.write( JSON.stringify( files ) );
resp.end();
return;
});
} else {
fs.readFile( file, function( error, content ) {
if ( error ) {
return write404( resp, req.path + ' not found' );
} else {
resp.writeHead( 200, {
'Content-Type': mime.lookup(req.path)
})
resp.write( content );
resp.end();
return;
}
});
}
})
})( fileName );
});
io.sockets.on( "connection", function( socket ) {
socket.emit( 'connected', { } )
});
function write404( resp, message ) {
resp.writeHead( 404, {} );
resp.write( message );
resp.end();
}
function write500( resp, message ) {
resp.writeHead( 500, {} );
resp.write( resp, "failed to upload image" );
resp.end();
}
app.listen( 8080 );