我試圖觀察某個目錄,當一個新檔案添加到該目錄時,我想重命名該檔案,但它不起作用。問題是目錄監視部分作業正常,但是當我重命名新添加的檔案時,我給它的名稱被迭代并給它錯誤的名稱。例如,如果我分配的新名稱是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`)
})
uj5u.com熱心網友回復:
我對您的代碼做了一些小的更改,它適用于任何檔案格式(也適用于未格式化的檔案)。無論如何,隨心所欲地使用。您唯一錯過的是“路徑”的用法:
const moment = require('moment');
const fs = require('fs');
const chokidar = require('chokidar');
const path = require('path');
const log = console.log.bind(console);
function formattedDate() {
return moment().format('YYYYMMDDHHmmss');
}
// here I've used some folder with name "folder" in the same directory as this file
const filePath = path.join(__dirname, `./folder`);
const watcher = chokidar.watch(filePath, {
ignored: /(^|[\/\\])\../,
persistent: true
});
watcher
.on('add', addedFilePath => {
const fileExt = path.extname(addedFilePath);
const newFilePath = path.join(__dirname, `./folder/${formattedDate()}${fileExt}`);
fs.renameSync(addedFilePath, newFilePath);
})
.on('change', changedFilePath => {
log(`File ${changedFilePath} has been changed`);
})
.on('unlink', removingFilePath => {
log(`File ${removingFilePath} has been removed`);
});
這是東西:

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/390878.html
標籤:节点.js
上一篇:使cmd區分角色的兩個if陳述句
下一篇:CastError:CasttoObjectId因值“ObjectId(610f16a6ba0d5fc2d4593093)”而失敗
