How to get the contents of a file as a String

2.3k views Asked by At

I am new to Typescript and node. I have this function

sftp.connect(config) //CONNECT TO STFP
.then(() => {
    sftp.list(remoteFilePath) //LIST THE FILES IN THE FILEPATH
        .then((list) => {
            list.forEach((index) => { //FOR EVERY FILE IN THE FOLDER, DOWNLOAD IT
                const fileName = remoteFilePath + index.name;
                console.log(fileName);
                sftp.fastGet(fileName, "/Users/Bob/" + index.name)
                    .then((value) => {
                        console.log(value);

                        sftp.end();
                    })
            })
        })
})
// .then(() => {
//     // sftp.end();
// })
.catch(err => {
    console.error(err.message);
});

and using the ssh2-sftp-client library. My question is that is it possible for this library to get the contents of the file as opposed to downloading it? I plan on making this function into a lambda function. At the moment, the variable value contains a text telling me that the file has been downloaded to my designated path.

1

There are 1 answers

0
Hex On

If you want to get the contents of the file you can read it using the fs module after downloading it

// using the ES6 module syntax
import { readFileSync } from "fs"


const data = readFileSync("./file.txt")

If you want to get the contents of the file without downloading them to the disk you have to pass a different destination. Use the ssh2-sftp-client get method instead, it accepts a Stream or a Buffer as the destination. You can use a Stream but you have to pipe it somewhere. Here's an example using process.stdout which is a writable stream:

// ...
stfp.get(
    fileName, "/Users/Bob/" + index.name,
    process.stdout
)