【发布时间】:2020-11-22 03:20:32
【问题描述】:
如果文件名已经存在于数据库中(也基于记录),我想为文件名增加一个数字。例如,如果我添加文件名为 DOC 的文件,它将检查 DOC 是否存在,因为下面的示例中存在 DOC 并且最新的增量为 1 (DOC-1),那么文件名将是 DOC-2。如果我再次添加 DOC 并且最新的增量是 2,那么新文件名将是 DOC-3.so 等等。有什么想法吗?谢谢。
听起来我想要的是始终创建一个新文件名(通过向文件名添加增量或数字),还可能在 .future 中找到多个相同数据更新的文件名。
#搜索记录是否存在的代码(工作正常)
const file = await context.service.Model.findOne({
where: { employeeId: record.id, filename: data.filename },
paranoid: false,
});
#更改文件名的代码(当前实现使用)
if (file) {
//this is where we add number to filename
filename = getNumberedFileName(data.filename)
}
#code 将数字添加到文件名
function getNumberedFileName(fileN) {
//These are value initializations to cope with the situation when the file does not have a .
var fileName = fileN;
var fileExtension = "";
var lastDotIndex = fileN.lastIndexOf(".");
if ((lastDotIndex > 0) && (lastDotIndex < fileN.length - 1)) { //We are not interested in file extensions for files without an extension hidden in UNIX systems, like .gitignore and we are not interested in file extensions if the file ends with a dot
fileName = fileN.substring(0, lastDotIndex);
fileExtension = "." + fileN.substring(lastDotIndex + 1);
}
var lastDashIndex = fileName.lastIndexOf("-");
if ((lastDashIndex > 0) && (lastDashIndex < fileName.length - 1)) {
var lastPart = fileName.substring(lastDashIndex + 1);
if (!isNaN(lastPart)) {
var index = parseInt(lastPart) + 1;
return fileName.substring(0, lastDashIndex) + "-" + index + fileExtension;
}
}
return fileName + "-1" + fileExtension;
}
【问题讨论】:
-
我已经用你的
makeUnique()到this earlier question 的函数回答了这个问题。 -
是否需要将文件查询的结果映射到makeUnique上?
-
您可以像普通函数一样调用
makeUnique(filename)。它是一个“正常”的功能。它会以您需要的格式返回文件名。(它“记住”您之前调用该函数的所有文件并计算一个合适的前缀。)我只使用.map机制来快速演示我的测试用例。 .. -
先生,另一个问题,makeUnique 将如何生成确切的文件名?我将如何将我的数据库记录基于函数?
-
正如我之前提到的,
makeUnique()将跟踪它在当前程序中收到的所有fn参数。它为此使用对象filenames,该对象保存在永久范围内。因此,只要您的 nodejs 应用程序正在运行,就会跟踪文件名并相应地计算前缀。当您重新启动您的应用程序时,filenames将再次作为一个空对象开始。
标签: javascript mysql node.js typescript sequelize.js