@@ -7,6 +7,8 @@ log.error = debug('cli:files:error')
7
7
var fs = require ( 'fs' )
8
8
const path = require ( 'path' )
9
9
const pathExists = require ( 'path-exists' )
10
+ const pull = require ( 'pull-stream' )
11
+ const toPull = require ( 'stream-to-pull-stream' )
10
12
11
13
function checkArgs ( hash , outPath ) {
12
14
// format the output directory
@@ -33,30 +35,39 @@ function ensureDir (dir, cb) {
33
35
. catch ( cb )
34
36
}
35
37
36
- function fileHandler ( result , dir ) {
37
- return function onFile ( file ) {
38
+ function fileHandler ( dir ) {
39
+ return function onFile ( file , cb ) {
40
+ const lastSlash = file . path . lastIndexOf ( '/' )
38
41
// Check to see if the result is in a directory
39
- if ( file . path . lastIndexOf ( '/' ) === - 1 ) {
42
+ if ( lastSlash === - 1 ) {
40
43
const dirPath = path . join ( dir , file . path )
41
44
// Check to see if the result is a directory
42
- if ( file . dir === false ) {
45
+ if ( file . content ) {
43
46
file . content . pipe ( fs . createWriteStream ( dirPath ) )
47
+ . once ( 'error' , cb )
48
+ . once ( 'end' , cb )
44
49
} else {
45
- ensureDir ( dirPath , ( err ) => {
46
- if ( err ) {
47
- throw err
48
- }
49
- } )
50
+ ensureDir ( dirPath , cb )
50
51
}
51
52
} else {
52
- const filePath = file . path . substring ( 0 , file . path . lastIndexOf ( '/' ) + 1 )
53
+ const filePath = file . path . substring ( 0 , lastSlash + 1 )
53
54
const dirPath = path . join ( dir , filePath )
55
+
54
56
ensureDir ( dirPath , ( err ) => {
55
57
if ( err ) {
56
- throw err
58
+ return cb ( err )
57
59
}
58
60
59
- file . content . pipe ( fs . createWriteStream ( dirPath ) )
61
+ if ( file . content ) {
62
+ const filename = file . path . substring ( lastSlash )
63
+ const target = path . join ( dirPath , filename )
64
+
65
+ file . content . pipe ( fs . createWriteStream ( target ) )
66
+ . once ( 'error' , cb )
67
+ . once ( 'end' , cb )
68
+ return
69
+ }
70
+ cb ( )
60
71
} )
61
72
}
62
73
}
@@ -76,17 +87,28 @@ module.exports = {
76
87
} ,
77
88
78
89
handler ( argv ) {
79
- const dir = checkArgs ( argv . ipfsPath , argv . output )
90
+ const ipfsPath = argv [ 'ipfs-path' ]
91
+ const dir = checkArgs ( ipfsPath , argv . output )
80
92
81
93
utils . getIPFS ( ( err , ipfs ) => {
82
94
if ( err ) {
83
95
throw err
84
96
}
85
- ipfs . files . get ( argv . ipfsPath , ( err , result ) => {
97
+
98
+ ipfs . files . get ( ipfsPath , ( err , stream ) => {
86
99
if ( err ) {
87
100
throw err
88
101
}
89
- result . on ( 'data' , fileHandler ( result , dir ) )
102
+ console . log ( `Saving file(s) to ${ ipfsPath } ` )
103
+ pull (
104
+ toPull . source ( stream ) ,
105
+ pull . asyncMap ( fileHandler ( dir ) ) ,
106
+ pull . onEnd ( ( err ) => {
107
+ if ( err ) {
108
+ throw err
109
+ }
110
+ } )
111
+ )
90
112
} )
91
113
} )
92
114
}
0 commit comments