繁体   English   中英

使用 node.js 和 Glob 将多个文件从 Google Cloud VM 上传到 Google Cloud Storage

[英]Uploading multiple files from a Google Cloud VM to Google Cloud Storage using node.js and Glob

我正在尝试使用 Node.js 将多个文件从我的 Google Compute Engine VM 本地目录上传到我已经创建的 GCS 存储桶。 每次运行脚本时都会出现以下错误。

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type function

剧本:

 `// Imports the Google Cloud client library const {Storage} = require('@google-cloud/storage'); const fs = require ('fs'); const glob = require('glob'); // The name of the bucket to access, eg "my-bucket" const bucketName = "myBucket"; // Instantiates a client const storage = new Storage({ projectId: 'myprojectID', keyFilename: 'my GCS service key' }); //get files in the local directory of VM var allfiles = glob('folder/*.js', function (err, files) { if (err) { console.log(err); } }); // Uploads VM local dir files to the bucket storage .bucket(bucketName) .upload(allfiles) .then(() => { console.log(`${allfiles} uploaded to ${bucketName}.`); }) .catch(err => { console.error('ERROR:', err); });'

显然,“上传”过程需要将文件路径名作为字符串。 但这正是 Glob 函数应该做的。 还是为什么会报错?

任何帮助将不胜感激!

您的错误是您使用allfiles作为glob的返回值。 这是不正确的,文件名在回调中可用(因为 glob 是异步的),而不是在返回值中。

glob('folder/*.js', function (err, files) { 
    if (err) { 
        console.log(err); 
    }

    var allfiles = files;

    // Uploads VM local dir files  to the bucket
   storage
  .bucket(bucketName)
  .upload(allfiles)
  .then(() => {
    console.log(`${allfiles} uploaded to ${bucketName}.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });'  
});

所以我终于让脚本工作了。 问题是,文件路径被捕获为一个对象,但 Google Cloud Storage 服务需要将路径作为字符串。

然后必须使用 JSON.stringify 将路径更改为字符串,然后拆分结果数组以仅选择文件路径内容。

 // Imports the Google Cloud client library const {Storage} = require('@google-cloud/storage'); const fs = require('fs'); var bucketName = 'intended GCS bucketname'; const storage = new Storage({ projectId: 'full project Id', keyFilename: 'cloud service key' }); //Invoke Glob for reading filepath in local/vm var glob = require('glob'); glob('path to local/vm directory', function (err, files) { if (err) { console.log(err); } var list = JSON.stringify(files) ; list = list.split('"') ; var listone = list[1] ; storage .bucket(bucketName) .upload(listone) .then(() => { console.log(`${listone} uploaded to ${bucketName}.`); }) .catch(err => { console.error('ERROR:', err); }); });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM