Rav*_*rti 7 firebase google-cloud-functions firebase-storage
我正在为我的webapp使用Cloud Functions for Firebase.我需要为在Firebase存储上上传的任何图片创建缩略图.为此,我需要将上传的文件从GCS存储桶下载到临时目录(使用mkdirp-promise),然后应用imageMagick命令创建缩略图.(Firebase功能样本 - 生成缩略图)
return mkdirp(tempLocalDir).then(() => {
console.log('Temporary directory has been created', tempLocalDir);
// Download file from bucket.
return bucket.file(filePath).download({
destination: tempLocalFile
});
}).then(() => {
//rest of the program
});
});
Run Code Online (Sandbox Code Playgroud)
我的问题是:
temp目录在哪里创建?tmpfs,该目录在Cloud Functions环境中保留在内存中。请参阅https://cloud.google.com/functions/pricing#local_disktmpfs已保存在内存中,因此该功能计入函数的内存使用量。fs.rmdir():https : //nodejs.org/api/fs.html#fs_fs_rmdir_path_callback以下是我为Google I/O中的"Fire!sale"持续部署演示编写的一些代码(警告:它是TypeScript,而不是JavaScript.这让我可以使用更容易阅读的await/async,特别是在错误处理)
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
let tempy = require('tempy'); // No .d.ts
function rmFileAsync(file: string) {
return new Promise((resolve, reject) => {
fs.unlink(file, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
})
})
}
function statAsync(file: string): Promise<fs.Stats> {
return new Promise((resolve, reject) => {
fs.stat(file, (err, stat) => {
if (err) {
reject(err);
} else {
resolve(stat);
}
})
})
}
async function rmrfAsync(dir: string) {
// Note: I should have written this to be async too
let files = fs.readdirSync(dir);
return Promise.all(_.map(files, async (file) => {
file = path.join(dir, file);
let stat = await statAsync(file);
if (stat.isFile()) {
return rmFileAsync(file);
}
return rmrfAsync(file);
}));
}
Run Code Online (Sandbox Code Playgroud)
然后在我的Cloud Functions代码中,我可以执行以下操作:
export let myFunction = functions.myTrigger.onEvent(async event => {
// If I want to be extra aggressive to handle any timeouts/failures and
// clean up before execution:
try {
await rmrfAsync(os.tmpdir());
} catch (err) {
console.log('Failed to clean temp directory. Deploy may fail.', err);
}
// In an async function we can use try/finally to ensure code runs
// without changing the error status of the function.
try {
// Gets a new directory under /tmp so we're guaranteed to have a
// clean slate.
let dir = tempy.directory();
// ... do stuff ...
} finally {
await rmrfAsync(dir);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2885 次 |
| 最近记录: |