@@ -7,6 +7,8 @@ log.error = debug('cli:files:error')
77var fs = require ( 'fs' )
88const path = require ( 'path' )
99const pathExists = require ( 'path-exists' )
10+ const pull = require ( 'pull-stream' )
11+ const toPull = require ( 'stream-to-pull-stream' )
1012
1113function checkArgs ( hash , outPath ) {
1214 // format the output directory
@@ -33,30 +35,39 @@ function ensureDir (dir, cb) {
3335 . catch ( cb )
3436}
3537
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 ( '/' )
3841 // Check to see if the result is in a directory
39- if ( file . path . lastIndexOf ( '/' ) === - 1 ) {
42+ if ( lastSlash === - 1 ) {
4043 const dirPath = path . join ( dir , file . path )
4144 // Check to see if the result is a directory
42- if ( file . dir === false ) {
45+ if ( file . content ) {
4346 file . content . pipe ( fs . createWriteStream ( dirPath ) )
47+ . once ( 'error' , cb )
48+ . once ( 'end' , cb )
4449 } else {
45- ensureDir ( dirPath , ( err ) => {
46- if ( err ) {
47- throw err
48- }
49- } )
50+ ensureDir ( dirPath , cb )
5051 }
5152 } else {
52- const filePath = file . path . substring ( 0 , file . path . lastIndexOf ( '/' ) + 1 )
53+ const filePath = file . path . substring ( 0 , lastSlash + 1 )
5354 const dirPath = path . join ( dir , filePath )
55+
5456 ensureDir ( dirPath , ( err ) => {
5557 if ( err ) {
56- throw err
58+ return cb ( err )
5759 }
5860
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 ( )
6071 } )
6172 }
6273 }
@@ -76,17 +87,28 @@ module.exports = {
7687 } ,
7788
7889 handler ( argv ) {
79- const dir = checkArgs ( argv . ipfsPath , argv . output )
90+ const ipfsPath = argv [ 'ipfs-path' ]
91+ const dir = checkArgs ( ipfsPath , argv . output )
8092
8193 utils . getIPFS ( ( err , ipfs ) => {
8294 if ( err ) {
8395 throw err
8496 }
85- ipfs . files . get ( argv . ipfsPath , ( err , result ) => {
97+
98+ ipfs . files . get ( ipfsPath , ( err , stream ) => {
8699 if ( err ) {
87100 throw err
88101 }
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+ )
90112 } )
91113 } )
92114 }
0 commit comments