【发布时间】:2022-01-24 01:25:24
【问题描述】:
我试图查看某个目录,当一个新文件添加到该目录时,我想重命名该文件,但它不起作用。问题是目录监视部分工作正常,但是当我重命名新添加的文件时,我给它的名称会被迭代并给它错误的名称。例如,如果我分配的新名称是thisIsName,当它被重命名时,它会变成thisIsNamethisIsNamethisIsNamethisIsName。我怎样才能使它重命名为指定的名称而无需任何迭代?任何帮助表示赞赏。提前致谢。
const fs = require("fs");
const chokidar = require('chokidar');
const watcher = chokidar.watch('filePath', {
ignored: /(^|[\/\\])\../,
persistent: true
});
function yyyymmdd() {
var now = new moment();
return now.format("YYYYMMDD");
}
function hhmmss() {
var now = new moment();
return now.format("HHmmss");
}
const log = console.log.bind(console);
//watching a certain directory for any update to it
watcher
.on('add', path => {
const newFileName = "filePath\\" + yyyymmdd() + hhmmss() + path
//trying to rename the file, but its not working because newFileName is somehow getting looped and having multiple iterations of the DATE and TIME in the new name when getting renamed. Example of what the product looks like is included above in the question.
fs.renameSync(path, newFileName);
})
.on('change', path => {
log(`File ${path} has been changed`)
})
.on('unlink', path => {
log(`File ${path} has been removed`)
})
【问题讨论】:
标签: node.js