使用可变字符串名称Nodejs创建Zip文件

问题描述 投票:0回答:1

我正在创建一个zip文件,其名称将基于GIT存储库哈希值和日期/时间。到目前为止,我已经能够成功创建zip文件,但是基于变量命名zip文件似乎不起作用,因为child_process.execFile似乎仅使用字符串文字作为名称。见下文:

const child_process = require('child_process').execFile;

const repoHash = (`git -C ./repository/myRepository show-ref --hash refs/heads/master`);
const timestamp = Date.now() - 14400000;
const date = new Date(timestamp);
const iso = date.toISOString().match(/(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})/);
const revision = child_process(repoHash).toString().trim();
const myTStamp = '_' + iso[1] + '_' + iso[2] + ".zip";

//Below zipName Resolves to "05baf31c20d15edb2c477fa4e7bd2427504d3dba_2020-04-09_13:27:26.zip"
const zipName = revision+myTStamp;  
const sourceDir = "./repository/myRepository";

//Works using a string literal and specifying name "./newZip.zip"
const newFile = () => {
    child_process('zip', ['-r', "./newZip.zip", sourceDir], function (err) {
        console.log(err);
    });
};

newFile();

//Does Not Work using "zipName" variable
const newFile = () => {
    child_process('zip', ['-r', zipName, sourceDir], function (err) {
        console.log(err);
    });
};

newFile();

任何有关如何获得此zip文件的想法都将得到赞赏。

javascript node.js variables zip filenames
1个回答
0
投票

正如Dr_Derp在他们的评论中所说,我不得不从那时开始删除“:”。我最终要做的是将“:”替换为“ _”,如下所示:

const repoHash = (`git -C ./repository/myRepository show-ref --hash refs/heads/master`);
const timestamp = Date.now() - 14400000;
const date = new Date(timestamp);
const iso = date.toISOString().match(/(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})/);
const revision = child_process(repoHash).toString().trim(); 
const sourceDir = "./repository/myRepository";

//Added 2 more variables to make it easier to read though new variables were not necessary
const time = iso[2].replace(/:/g, "_");
const date = iso[1];
//Output of "myTStamp" below:  05baf31c20d15edb2c477fa4e7bd2427504d3dba_DATE_2020-04-09_TIME_14_54_15.zip
const myTStamp = '_DATE_' + date + '_TIME_' + time + ".zip";
const zipName = revision+myTStamp;

const newFile = () => {
    child_process('zip', ['-r', zipName, sourceDir], function (err) {
        console.log(err);
    });
};

newFile();

再次感谢Dr_Derp!

© www.soinside.com 2019 - 2024. All rights reserved.