![](/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.