Search code examples
javascriptnode.jsasync-awaites6-promisefs

Write createWriteStream txt contents to a global variable with Node.js


I am trying to download txt and mp3 files and use the content of them in another node module.

How can I create a global variable with the piped contents from the downloaded txt (and MP3 at a later stage) file to use outside of the FTP function?

async function example() {
    var finalData = '';

    const client = new ftp.Client()
    client.ftp.verbose = true
    try {
    await client.access({
        host: "XXXX",
        user: "XXXX",
        password: "XXXX",
    })


    await client.upload(fs.createReadStream("README.txt"), myFileNameWithExtension)
    //let writeStream = fs.createWriteStream('/tmp/' + myFileNameWithExtension);
    //await client.download(writeStream, myFileNameWithExtension)

    finalData = await (() => {
        return new Promise((resolve, reject) => {

        writeStream
            .on('finish', () => {

            // Create a global variable to  be used outside of the FTP function scope to pipe the txt content into another node mogule

            })
            .on('error', (err) => {
            console.log(err);
            reject(err);
            })
        })
    })();
    }
    catch (err) {
    console.log(err)
    }
    client.close();
    return finalData;
}

Solution

  • No, don't create any global variables. Just resolve the promise with the data:

    var finalData = await new Promise((resolve, reject) => {
        writeStream.on('finish', () => {
            resolve(); // pass a value
        }).on('error', (err) => {
            reject(err);
        });
    });
    

    The finalData will become whatever value you pass into resolve(…) - I don't know what result you want to pass there. In the end, just return the data from your example function (as you already do), so that the caller will be able to use it after waiting for the returned promise.