rename file name before download nodejs code example
Example 1: rename a file using node.js
const { join } = require('path');
const { readdirSync, renameSync } = require('fs');
const [dir, search, replace] = process.argv.slice(2);
const match = RegExp(search, 'g');
const files = readdirSync(dir);
files
.filter(file => file.match(match))
.forEach(file => {
const filePath = join(dir, file);
const newFilePath = join(dir, file.replace(match, replace));
renameSync(filePath, newFilePath);
});
Example 2: nodejs copy and rename file
var copyFile = (file, dir2)=>{
var fs = require('fs');
var path = require('path');
var f = path.basename(file);
var source = fs.createReadStream(file);
var dest = fs.createWriteStream(path.resolve(dir2, f));
source.pipe(dest);
source.on('end', function() { console.log('Succesfully copied'); });
source.on('error', function(err) { console.log(err); });
};
copyFile('./test/dir_1/file1.htm', './test/');