convert readable stream to save it as a file in local
Asked Answered
W

2

8

I am using ssh2-sftp-client to get the file from remote server. I am getting the file in readable stream. I want to convert this readable stream to the desired file (sample.png as a png file, sample.doc file as doc file etc.)

Here is my code-

let Client = require('ssh2-sftp-client');
let sftp = new Client();
 sftp.connect({
    host: sftpCredentials.host,
    port: sftpCredentials.port,
    username: sftpCredentials.username,
    password: sftpCredentials.password
}).then(res => sftp.list('/'))
.then(res => {
     const file = await sftp.get('/sample.png');

})

i want to save this file in local. File is a readable stream as follows -

ReadStream {_readableState: ReadableState, readable: true, domain: null, _events: Object, _eventsCount: 3, …}
    _events:Object {end: , error: , readable: }
    _eventsCount:3
    _maxListeners:undefined
    _readableState:ReadableState {objectMode: false, highWaterMark: 65536, buffer: BufferList, …}
    autoClose:true
    destroyed:false
    domain:null
    end:undefined
    flags:"r"
    handle:Buffer(4) [0, 0, 0, …]
    mode:438
    path:"/sample.png"
    pos:131072
    readable:true
    readableHighWaterMark:65536
    sftp:SFTPStream {_readableState: ReadableState, readable: true, domain: null, …}
    start:undefined
    __proto__:Readable {open: , _read: , destroy: , …}
Willaims answered 19/12, 2018 at 6:27 Comment(0)
E
7

As file is a readable stream,you can try

let Client = require('ssh2-sftp-client');
    let fsv=vrequire('fs');
    let sftp = new Client();
     sftp.connect({
        host: sftpCredentials.host,
        port: sftpCredentials.port,
        username: sftpCredentials.username,
        password: sftpCredentials.password
    }).then(res => sftp.list('/'))
    .then(async res => {
         const file = await sftp.get('/sample.png');
         const ws=fs.createWriteStream('sample.png');
         file.pipe(ws);
         file.on('end',()=>console.log('done'));
    })
Egon answered 19/12, 2018 at 7:16 Comment(4)
This is not giving me the file in correct format. The saved file is not displaying the imageWillaims
@Komal Bansal .Set Encoding to null by const file = await sftp.get('/sample.png',false,null);Egon
Can i also then this file to user without saving it using res.download? @EgonWillaims
@Komal Bansal .Of course,res.setHeader('Content-Disposition','attachment; filename="sample.png"');file.pipe(res)Egon
A
0

If anybody still ends up here trying to save a ReadableStream to a file, there's an easier way since v15.14.0, v14.18.0.

It's possible to use fsPromises.writeFile directly with a stream:

import fs from 'fs/promises';

const stream = await sftp.get('/sample.png');
await fs.writeFile('./sample.png', stream);
Acrylonitrile answered 5/9 at 23:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.