在使用节点JS10的Google函数中使用file.length时,我得到以下错误:
TextPayload:“TypeError[ERR_INVALID_ARG_TYPE]:”path“参数必须是string、Buffer或URL类型之一。已接收类型对象”
我现在的代码如下:
const {Storage} = require('@google-cloud/storage');
const {path} = require('path');
var fs = require('fs');
exports.copyRenders = (event, context) => {
const gcsEvent = event;
const sourcePathOnly = gcsEvent.name
const sourceFolder = sourcePathOnly.split('/').slice(-2)
fs.readdir(sourceFolder, (err, files) => {
console.log(files.length);
//console.log(`Files are: ${sourceFolder}`);
});
}
我在这里做错了什么?
谢谢
尝试添加.join(“”)
使您的SourceFolder
常量成为字符串,在我看来您用.slice
使它成为数组
exports.copyRenders = (event, context) => {
const gcsEvent = event;
const sourcePathOnly = gcsEvent.name
const sourceFolder = sourcePathOnly.split('/').slice(-2)
.join("") // <- here
fs.readdir(sourceFolder, (err, files) => {
//console.log(files.length);
console.log(`Files are: ${sourceFolder}`);
});
}
在云存储中没有文件夹这里解释了目录是如何工作的,因为它们只是对象的较长名称,包括目录/子目录/对象名。
因此,获取目录中所有元素的通常方法都不起作用,下面是一个在桶上列出对象的示例,以及列出共享前缀的对象的方法(在同一目录中)。
下面是如何获取桶上共享前缀的文件的数量。
async function countFilesByPrefix(bucketName, prefix) {
// [START storage_list_files_with_prefix]
// Imports the Google Cloud client library
const storage = require('@google-cloud/storage')();
const options = {
prefix: prefix,
};
const [files] = await storage.bucket(bucketName).getFiles(options);
console.log(` Number of Files ${ files.length}`);
}