1
+ /**
2
+ * Multipart example downloading all the files to disk using co-busboy.
3
+ * If all you want is to download the files to a temporary folder,
4
+ * just use https://github.com/cojs/multipart instead of copying this code
5
+ * as it handles file descriptor limits whereas this does not.
6
+ */
7
+
1
8
var os = require ( 'os' ) ;
2
9
var path = require ( 'path' ) ;
3
10
var fs = require ( 'fs' ) ;
4
11
var koa = require ( 'koa' ) ;
5
12
var parse = require ( 'co-busboy' ) ;
6
13
var saveTo = require ( 'save-to' ) ;
7
- var archan = require ( 'archan' ) ;
8
14
9
15
var app = module . exports = koa ( ) ;
10
16
11
17
app . use ( function * ( ) {
12
- // create a go-like channel for control flow
13
- var ch = archan ( {
14
- concurrency : 1 // save only 1 file at a time
15
- } ) ;
16
-
17
18
// parse the multipart body
18
19
var parts = parse ( this , {
19
20
autoFields : true // saves the fields to parts.field(s)
20
21
} ) ;
21
22
22
23
// create a temporary folder to store files
23
- var tmpdir = path . join ( os . tmpdir ( ) , Math . random ( ) . toString ( 36 ) . slice ( 2 ) ) ;
24
+ var tmpdir = path . join ( os . tmpdir ( ) , uid ( ) ) ;
24
25
25
26
// make the temporary directory
26
27
yield fs . mkdir . bind ( null , tmpdir ) ;
27
28
29
+ // list of all the files
30
+ var files = [ ] ;
31
+ var file ;
32
+
28
33
// yield each part as a stream
29
34
var part ;
30
35
while ( part = yield parts ) {
31
- // wait if there are too many file descriptors opened
32
- yield * ch . drain ( ) ;
33
- // save each part to a file,
34
- // but do it in a different channel
35
- // so we don't block this particular while loop.
36
- saveTo ( part , path . join ( tmpdir , part . filename ) , ch . push ( ) ) ;
36
+ // filename for this part
37
+ files . push ( file = path . join ( tmpdir , part . filename ) )
38
+ // save the file
39
+ yield saveTo ( part , file ) ;
37
40
}
38
41
39
42
// return all the filenames as an array
40
43
// after all the files have finished downloading
41
- this . body = yield * ch . flush ( ) ;
44
+ this . body = files ;
42
45
} )
43
46
44
- if ( ! module . parent ) app . listen ( 3000 ) ;
47
+ if ( ! module . parent ) app . listen ( 3000 ) ;
48
+
49
+ function uid ( ) {
50
+ return Math . random ( ) . toString ( 36 ) . slice ( 2 ) ;
51
+ }
0 commit comments