google storage api | upload files to google cloud | test upload files to google storage | Search

This code provides a function copyFileBucket that copies a file within a Google Cloud Storage bucket, utilizing Google Cloud APIs for authentication and file manipulation.

Run example

npm run import -- "copy a file in storage bucket"

copy a file in storage bucket

var importer = require('../Core');
var authorizeGoogle = importer.import("authorize google service");
var project = 'spahaha-ea443';
var qs = require('querystring');

function copyFileBucket(bucket, file) {
    var params = {project: project};
    console.log('copying file:', file)
    return authorizeGoogle()
        .then(client => client.request({
            method: 'POST',
            url: `https://www.googleapis.com/storage/v1/b/${bucket}/o/${qs.escape(file)}/rewriteTo/b/${bucket}/o/${qs.escape(file.replace(/\.html|\.htm/ig, ''))}`,
            params
        }))
}

module.exports = copyFileBucket;

What the code could have been:

// Import required modules and define constants
const importer = require('../Core');
const authorizeGoogle = importer.import('authorize google service');
const qs = require('querystring');
const PROJECT_ID ='spahaha-ea443';

/**
 * Copies a file in a Google Cloud Storage bucket.
 * 
 * @param {string} bucket - The ID of the Google Cloud Storage bucket.
 * @param {string} file - The name of the file to copy.
 * @returns {Promise} A promise that resolves when the file has been copied.
 */
async function copyFileBucket(bucket, file) {
    // Validate input parameters
    if (!bucket ||!file) {
        throw new Error('Both bucket and file are required');
    }

    // Construct the URL for the Copy request
    const url = `https://www.googleapis.com/storage/v1/b/${bucket}/o/${qs.escape(file)}/rewriteTo/b/${bucket}/o/${qs.escape(file.replace(/\.html|\.htm/ig, ''))}`;

    // Make the Copy request
    const client = await authorizeGoogle();
    return client.request({
        method: 'POST',
        url,
        params: { project: PROJECT_ID }
    });
}

module.exports = copyFileBucket;

This code defines a function copyFileBucket that copies a file from one location to another within a Google Cloud Storage bucket.

Here's a breakdown:

  1. Imports:

  2. Constants:

  3. copyFileBucket Function:

  4. Export: