Olawale Isaac
Olawale Isaac

Reputation: 53

How to write a file to Google Cloud Storage directly without saving it in my application?

I am trying to write an HTML file into Google Cloud Storage without saving the file in my node application. I need to create a file and immediately upload to the Cloud Storage. I tried using fs.writeFileSync() method, but it creates the file in my application and I do not want that.

const res = fs.writeFileSync("submission.html", fileData, "utf8");
GCS.upload(res, filePath);

I expect to save an HTML file in the Cloud Storage directly. Could you please recommend the right approach to me?

Upvotes: 3

Views: 1994

Answers (1)

Bhavay Anand
Bhavay Anand

Reputation: 335

The solution I believe is to use the file.save method that wraps createWriteStream, so this should work.

const storage = require('@google-cloud/storage')();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');
const contents = 'This is the contents of the file.';

file.save(contents, function(err) {
  if (!err) {
    // File written successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.save(contents).then(function() {});

Upvotes: 6

Related Questions