Create a new file in google bucket nodejs
Here is an example of how to create a new file in a Google Cloud Storage bucket using Node.js:
const {Storage} = require('@google-cloud/storage');
// Create a client instance
const storage = new Storage();
// Set the bucket name and file name
const bucketName = 'your-bucket-name';
const fileName = 'new-file.txt';
// Create a new file
storage.bucket(bucketName).file(fileName, (err, file) => {
if (err) {
console.error('Error creating file:', err);
return;
}
console.log(`File created: ${file.name}`);
});
This code uses the @google-cloud/storage
library to create a client instance and interact with the Google Cloud Storage API.
You'll need to replace your-bucket-name
with the actual name of your bucket.
You can also specify the file contents by passing a string or a buffer to the create
method:
storage.bucket(bucketName).file(fileName, 'Hello, world!', (err, file) => {
//...
});
Or:
const buffer = Buffer.from('Hello, world!');
storage.bucket(bucketName).file(fileName, buffer, (err, file) => {
//...
});
Make sure to install the @google-cloud/storage
library by running npm install @google-cloud/storage
or yarn add @google-cloud/storage
in your project directory.
Also, you need to have the GOOGLE_APPLICATION_CREDENTIALS
environment variable set with the path to your service account key file. You can do this by running export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/service_account_key.json
(on Linux/macOS) or set GOOGLE_APPLICATION_CREDENTIALS=C:\path\to\your\service_account_key.json
(on Windows).
Once you've set up the environment variable, you can run the code above to create a new file in your Google Cloud Storage bucket.