Jinko
Jinko

Reputation: 3

NODE.JS : How to make sure a reading stream has ended and the data written?

so I am new to async/await on node.js and I could use some help figuring out this code.

I'm trying to get a file from a ftp server via the 'ftp' package, to write the data into a local 'data.txt' and to open it later in the code. My problem is that I don't understand how to make sure the file is completely written in the 'data.txt' before trying to open it with fs.readFileSync().

const ConfigFTP = require('./credentials.json')
const FtpClient = new ftpclient();


FtpClient.on('ready', async function() {
    await new Promise(resolve =>
      FtpClient.get('the ftp file directory', (err, stream) => {
        if (err) throw err;
        stream.once('close', () => {FtpClient.end();});
        // Stream written in data.txt
        const Streampipe = stream.pipe(fs.createWriteStream('data.txt')).on('finish', resolve)
      })
    )
})
FtpClient.connect(ConfigFTP);
var Data = fs.readFileSync('data.txt', 'utf8');

Upvotes: 0

Views: 588

Answers (1)

sausage
sausage

Reputation: 101

I'm not sure what you want to accomplish, but you can do something like these:

1)

const ConfigFTP = require('./credentials.json')
const FtpClient = new ftpclient()

let writeStream = fs.createWriteStream('data.txt')

FtpClient.on('ready', async function () {
    FtpClient.get('the ftp file directory', (err, stream) => {
            if (err) throw err
            stream.once('close', () => { FtpClient.end() })
            // Stream written in data.txt
            const Streampipe = stream.pipe(writeStream)
    })
})
FtpClient.connect(ConfigFTP)

writeStream.on('finish', () => {
    var Data = fs.readFileSync('data.txt', 'utf8')
})

2)

const ConfigFTP = require('./credentials.json')
const FtpClient = new ftpclient()


FtpClient.on('ready', async function() {
    await new Promise(resolve =>
      FtpClient.get('the ftp file directory', (err, stream) => {
        if (err) throw err
        stream.once('close', () => {FtpClient.end()})
        // Stream written in data.txt
        const Streampipe = stream.pipe(fs.createWriteStream('data.txt')).on('finish', resolve)
      })
    )
    var Data = fs.readFileSync('data.txt', 'utf8')
})
FtpClient.connect(ConfigFTP)

Upvotes: 2

Related Questions