-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
63 lines (48 loc) · 1.4 KB
/
index.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
var path = require( 'path' );
var fs = require( 'fs' );
var mime = require( 'mime' );
module.exports = connectGobble;
function connectGobble ( node ) {
var task;
if ( typeof node === 'string' ) {
node = require( path.resolve( node ) );
}
if ( !node || !node._gobble ) {
throw new Error( 'You must supply a build definition to connect-gobble' );
}
task = node.watch({
dest: '.connect-gobble'
});
task.on( 'error', function ( err ) {
console.error( err ); // TODO how is middleware *supposed* to handle these sorts of errors?
});
return function ( req, res, next ) {
var filepath = path.join( '.connect-gobble', req.url );
fs.stat( filepath, function ( err, stats ) {
var indexpath;
if ( err ) return next();
if ( stats.isDirectory() ) {
// try to serve index.html file
indexpath = path.join( filepath, 'index.html' );
fs.stat( indexpath, function ( err, stats ) {
if ( err ) return next();
// ensure trailing '/'
if ( req.url.slice( -1 ) !== '/' ) {
res.redirect( req.url + '/' );
return;
}
// set mime type
res.setHeader( 'content-type', 'text/html' );
// stream file contents
fs.createReadStream( indexpath ).pipe( res );
});
}
else {
// set mime type
res.setHeader( 'content-type', mime.lookup( filepath ) );
// stream file contents
fs.createReadStream( filepath ).pipe( res );
}
});
};
}