I have a rather strange problem reading threads in Node.js. I use SSH2 to create an sftp connection between me and the sftp server. Then I try to create a read stream from the sftp stream. From the data stream passed to the read stream, I add data to the array. When the close event of the read stream occurs, I make a call to Buffer.concat to create concat all the pieces of data that I received in one buffer. This is the same method described in other questions asked here when stack overflows. For example here . However, I cannot use the data I retrieve. It looks like the buffer size is 32 bytes smaller than the file I'm trying to extract (from counting the length of the extracted data). Could this have anything to do with my SFTP connection? Or how do I create my read stream?
If it matters, the file is of type zip. When I try to unzip a file (in Node.js and manually) after reading it to the buffer, it does not work.
After the study, it turned out that:
- When I use readdir in a file, the file size is correct.
- Using FTP (JSFTP) against my development FTP server is working fine using the same method above.
Any advice is appreciated!
Here is my code:
var Client = require('ssh2').Client; var m_ssh2Credentials = { host: config.ftpHostName, port: config.ftpPort, username: config.ftpUser, password: config.ftpPassword, readyTimeout: 20000, algorithms: { cipher: ["3des-cbc", "aes256-cbc", "aes192-cbc","aes128-cbc"]} }; ... var conn = new Client(); var dataLength = 0; conn.on('ready', function() { conn.sftp(function(err, sftp) { if (err) { writeToErrorLog("downloadFile(): Failed to open SFTP connection."); } else { writeToLog("downloadFile(): Opened SFTP connection."); } var streamErr = ""; var dataLength = 0; var stream = sftp.createReadStream(config.ftpPath + "/" + m_fileName) stream.on('data', function(d){ data.push(d); dataLength += d.length; }); .on('error', function(e){ streamErr = e; }) .on('close', function(){ if(streamErr) { writeToErrorLog("downloadFile(): Error retrieving the file: " + streamErr); } else { writeToLog("downloadFile(): No error using read stream."); m_fileBuffer = Buffer.concat(data, dataLength); writeToLog("Data length: " + dataLength); writeToLog("downloadFile(): File saved to buffer."); } conn.end(); }); }) }) .on('error', function(err) { writeToErrorLog("downloadFile(): Error connecting: " + err); }).connect(m_ssh2Credentials);
source share