使用NodeJS从Google Cloud Storage Bucket下载文件夹 [英] Downloading folders from Google Cloud Storage Bucket with NodeJS

查看:132
本文介绍了使用NodeJS从Google Cloud Storage Bucket下载文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从Google Cloud Storage的存储桶中下载带有NodeJS的文件夹.我阅读了所有文档,仅找到一种下载文件而不下载文件夹的方法.我需要获取/下载该文件夹以提供用户的下载文件.

I need to download folders with NodeJS from my Bucket from my Google Cloud Storage. I read all the documentation and I only found a way to download files and not folders. I need to get/download the folder to provide user's download files.

有人可以帮我吗?

推荐答案

正如Doug所说,Google Cloud Storage会向您显示不同目录的结构,但实际上存储桶中没有文件夹.

As Doug said, Google Cloud Storage would show you the structure of different directories, but there are actually no folders within the buckets.

但是,您可以在代码中找到一些解决方法,以自己创建完全相同的文件夹结构.对于我想出的解决方法,您需要使用诸如 shelljs 之类的库,您可以在系统中创建文件夹.

However, you can find perform some workarounds within your code to create that very same folder structure yourself. For the workaround I came up with, you need to use libraries such as shelljs, which will allow you to create folders in your system.

按照此有关Cloud Storage的GCP教程,您会发现例如有关如何从存储桶中列出或下载文件的示例.

Following this GCP tutorial on Cloud Storage, you will find examples on, for instance, how to list or download files from your bucket.

现在,将所有这些放在一起,您可以获得要下载的文件的完整路径,将其解析以将文件夹与实际文件分开,然后使用Shelljs中的方法mkdir创建文件夹结构.

Now, putting all this together, you can get the full path of the file you are going to download, parse it to separate the folders from the actual file, then create the folder structure using the method mkdir from shelljs.

对我来说,修改本教程中的文件下载方法是这样的:

For me, modifying the method for downloading files in the tutorial, was something like this:

var shell = require('shelljs');
[...]
async function downloadFile(bucketName, srcFilename, destFilename) {
  // [START storage_download_file]
  // Imports the Google Cloud client library
  const {Storage} = require('@google-cloud/storage');

  // Creates a client
  const storage = new Storage();

  //Find last separator index
  var index = srcFilename.lastIndexOf('/');
  //Get the folder route as string using previous separator
  var str = srcFilename.slice(0, index);
  //Create recursively the folder structure in the current directory
  shell.mkdir('-p', './'+str);
  //Path of the downloaded file
  var destPath = str+'/'+destFilename;

  const options = {
    destination: destPath,
  };

  // Downloads the file
  await storage
    .bucket(bucketName)
    .file(srcFilename)
    .download(options);

  console.log(
    `gs://${bucketName}/${srcFilename} downloaded to ${destPath}.`
  );
  // [END storage_download_file]
}

这篇关于使用NodeJS从Google Cloud Storage Bucket下载文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆