Home > Software design >  Renaming file not having proper assigned name
Renaming file not having proper assigned name

Time:12-23

I was trying to watch a certain directory and when a new file is added to that directory I want to rename the file but it's not working. The problem is the directory watching part works fine but when I rename the newly added file the name I am giving it is iterated and giving it the wrong name. For Example, if the new name I'm assigning is thisIsName when it gets renamed it becomes thisIsNamethisIsNamethisIsNamethisIsName. How can I make it so that the rename is the assigned name without any iteration? Any help is appreciated. Thanks in advance.

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`)
  })

CodePudding user response:

I've done some small changes in your code and it worked for me for any file formats (for unformatted files as well). Anyway, use as you want. The only thing you've missed, was the usage of "path":

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`);
    });

Here is the stuff:

enter image description here

  • Related