【问题标题】:Create Zip File w/ variable string name Nodejs创建带有变量字符串名称 Nodejs 的 Zip 文件
【发布时间】:2020-04-09 17:33:25
【问题描述】:

我正在创建一个 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 文件的想法将不胜感激。

【问题讨论】:

  • 文件名可能有问题,可能包含无效字符?您是否尝试过将 zipName 的全部值放入第一个函数中的文字中?那样有用吗?第二个函数是否返回错误?错误是什么?
  • 哇...我的菜鸟表现出来了...不敢相信我没想到...是的!它不喜欢日期/时间......一旦我把它拿出来,我就可以使用变量......让我看看“typeof”日期/时间是什么,如果它是对象.....谢谢...这很有帮助....
  • 很高兴能帮上忙 :)

标签: javascript node.js variables zip filenames


【解决方案1】:

正如 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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多