Istiak Mahmood
Istiak Mahmood

Reputation: 2422

Send CSV file from Google bucket to SFTP server using GCP Cloud function NodeJS

I am trying to send a csv file to a SFTP server using a Google Cloud Function. This means -

Step 1 - need to Create a Connection with the SFTP Server

Step 2- Pick the csv File from the GCP Bucket

Step 3 - Push the File to SFTP Server in a certain location

This is the nodejs script I am using -

exports.helloWorld = (req, res) => {
  let Client = require('ssh2-sftp-client');
  let sftp = new Client();

sftp.connect({
  host: process.env.SFTP_SERVER,
  username: process.env.SFTP_USER,
  port: process.env.SFTP_PORT,
  password: process.env.SFTP_PASSWORD
}).then(() => {
  return sftp.list('/public');
}).then(data => {
  console.log(data, 'the data info');
}).catch(err => {
  console.log(err, 'catch error');
});
};

And this is my Package.json file

{
  "name": "sample-http",
  "version": "0.0.1",
  "dependencies": {
    "node-fetch": "^2.6.0",
    "@google-cloud/bigquery": "5.10.0",
    "@google-cloud/storage": "5.18.0",
    "ssh2-sftp-client": "7.2.1"
    
  }
}

Now Everything runs fine but it doesn't do anything. Can anyone point to me what script I am missing here and if there is any documentation to do the following steps??

Upvotes: 1

Views: 525

Answers (1)

David
David

Reputation: 9721

Because the SFTP code is all async, your function is probably returning before the .then() has run and your execution environment is ending before the it gets to upload the file. You should make your helloWorld function async and await and return a response before returning:

exports.helloWorld = async (req, res) => {
  // ...
  await sftp.connect({
    // ...
  });
  res.send(200);
  res.end();
};

Upvotes: 2

Related Questions