Загрузка нескольких файлов из виртуальной машины Google Cloud в облачное хранилище Google с использованием node.js и Glob

Я пытаюсь Node.js загрузить несколько файлов из локального каталога моей виртуальной машины Google Compute Engine в корзину 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, e.g. "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. И все же почему ошибка?

Любая помощь будет серьезно оценена!


person AliveToLearn    schedule 07.11.2018    source источник


Ответы (2)


Ваша ошибка в том, что вы используете 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);
  });'  
});
person mihai    schedule 07.11.2018
comment
Привет @mihai, большое спасибо за ваш ответ. Я считаю, что он правильно устанавливает контекст кода, но я все еще получаю ту же ошибку после реализации ваших предложений... - person AliveToLearn; 08.11.2018
comment
что печатает console.log(allfiles)? - person mihai; 08.11.2018
comment
Он печатает путь к файлу. - person AliveToLearn; 27.11.2018
comment
вы уверены, что получаете ту же ошибку, а не что-то еще? - person mihai; 27.11.2018

Итак, я наконец заставил скрипт работать. Проблема заключалась в том, что путь к файлу захватывался как объект, но сервису 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);
		         });  

 
});

person AliveToLearn    schedule 27.11.2018