Beginner coder here, so apologies in advance for any messy code or lack of understanding!
I'm writing a small automation code with Node.js that uses a webhook to create a quick CSV file in a SFTP location. I have most of the base code written out but I'm having an issue when I run it locally. Right now, the code runs, connects to an SFTP using ssh2-sftp-client, opens a stream, and writes the CSV file directly into the SFTP path. This all works how I need it to, except the code hangs on an error:
_put: File is already exclusively open. <stream>
The code actually does write the file directly into the SFTP path, but the file isn't openable due to the same error in FileZilla: File is already exclusively open. I have to force quit the code in order for the file to be accessible. I'm assuming I just have to close the stream/file in my code, but I can't quite figure out how to do so. The stream function I'm using is part of the ssh2-sftp-client package, but I can't find any documentation on how to close out the stream in their package website. Here is the code for reference:
//quick function to assign a random number to my CSV file name
function randomNumber() {
return Math.floor(
Math.random() * (999999999-100000000) + 100000000
)
}
//assign name and .extension to csv file
var csvName = randomNumber() + '.csv';
//this is the data the ssh2-sftp module will use to connect to my SFTP server
const Client = require('ssh2-sftp-client');
const config = {
//running a local test sftp server here
host: 'xxx.xxx.x.xxx',
port: 2222,
username: 'tester',
password: 'password'
};
const fs = require("fs");
//this is the code that uses the config above to connect to the sftp server and upload the local file.
let client = new Client();
let remote = csvName;
client.connect(config)
.then(() => {
let data = client.createWriteStream(csvName);
let data2 = client.createReadStream(csvName);
data.write('FirstName,LAstName\r\nTesting,Testing\r\n123,456,3333333');
return client.put(data2, remote);
})
.then(() => {
return client.end();
})
.catch(err => {
console.error(err.message);
});
I'm assuming my main issue is in the ssh2-sftp-client functions createWriteStream and createReadStream, but I haven't been able to figure it out!
Thanks in advance!