![](/img/trans.png)
[英]Creating a zip archive from a folder and preserving structure with Node.js
[英]How to copy and zip folder from stream rather than disk- Node.js
我下面的代碼在替換了一些變量后將/template
目錄復制到/theme
目錄中。
/theme
目錄被壓縮並在 HTTP 響應中返回。
這可以在本地工作,但是一旦我將其推送到 Netlify 就會失敗。 它失敗了,因為我沒有 function 中的寫權限。 我相信解決方案是寫入 stream 而不是磁盤,但在閱讀了一些文檔后我不確定如何做到這一點。
const copy = require("copy-template-dir");
const path = require("path");
const fs = require("fs");
const JSZip = require("jszip");
const inDir = path.join(__dirname, "template");
const outDir = path.join(__dirname, "theme");
exports.handler = async (event, context) => {
// Searches /template, replaces the variables, and copies the files to /theme
function makeCopy() {
return new Promise(function (resolve, reject) {
//returning promise
// Theme Variables to Find and Replace
const vars = {
theme_name: "Theme Name",
theme_slug: "theme-slug",
author_name: "Author Name",
};
// Get vars from query string
if (event.queryStringParameters) {
vars.theme_name = event.queryStringParameters.name || vars.theme_name;
vars.theme_slug = event.queryStringParameters.name || vars.theme_slug;
vars.author_name = event.queryStringParameters.author || vars.author_name;
}
copy(inDir, outDir, vars, (err, createdFiles) => {
if (err) throw err;
resolve();
});
});
}
// Loops contents of the /theme directory and creates a zip file
const addFilesFromDirectoryToZip = (directoryPath = "", zip) => {
const directoryContents = fs.readdirSync(directoryPath, {
withFileTypes: true,
});
directoryContents.forEach(({ name }) => {
const path = `${directoryPath}/${name}`;
if (fs.statSync(path).isFile()) {
zip.file(path, fs.readFileSync(path, "utf-8"));
}
if (fs.statSync(path).isDirectory()) {
addFilesFromDirectoryToZip(path, zip);
}
});
};
// Zip the theme
async function makeZip() {
var zip = new JSZip();
addFilesFromDirectoryToZip("theme", zip);
const zipAsBase64 = await zip.generateAsync({ type: "base64" });
return zipAsBase64;
}
const myCopy = await makeCopy();
const zip = await makeZip();
// Return the zip
return {
statusCode: 200,
body: zip,
headers: {
"Content-Type": "application/zip",
"Content-Disposition": "attachment; filename=theme.zip",
},
};
};
答案不是節點流。 由於這是 lambda function,我只需要使用可寫 /tmp 文件夾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.