简体   繁体   中英

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'); 

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM