常用的JavaScript脚本,用于执行日常任务

1.批量重命名文件
const fs = require('fs');
const path = require('path');

function batchRename(folder, prefix) {
  fs.readdir(folder, (err, files) => {
    if (err) throw err;
    files.forEach((file, index) => {
      const ext = path.extname(file);
      const oldPath = path.join(folder, file);
      const newPath = path.join(folder, `${prefix}_${String(index).padStart(3, '0')}${ext}`);
      fs.rename(oldPath, newPath, (err) => {
        if (err) throw err;
        console.log(`Renamed ${file} to ${path.basename(newPath)}`);
      });
    });
  });
}
batchRename('/path/to/files', 'image');
2.将多个 PDF 合并为一个
const fs = require('fs');
const PDFMerger = require('pdf-merger-js');

async function mergePDFs(pdfFolder, outputPDF) {
  const merger = new PDFMerger();
  const files = fs.readdirSync(pdfFolder).filter((file) => file.endsWith('.pdf'));
  for (const file of files) {
    await merger.add(path.join(pdfFolder, file));
  }
  await merger.save(outputPDF);
  console.log(`Merged PDFs into ${outputPDF}`);
}
mergePDFs('/path/to/pdfs', 'merged_document.pdf');
3.自动清理旧文件
const fs = require('fs');
const path = require('path');

function cleanOldFiles(folder, days) {
  const now = Date.now();
  const cutoff = now - days * 24 * 60 * 60 * 1000;
  fs.readdir(folder, (err, files) => {
    if (err) throw err;
    files.forEach((file) => {
      const filePath = path.join(folder, file);
      fs.stat(filePath, (err, stat) => {
        if (err) throw err;
        if (stat.mtime.getTime() < cutoff) {
          fs.unlink(filePath, (err) => {
            if (err) throw err;
            console.log(`Deleted ${file}`);
          });
        }
      });
    });
  });
}
cleanOldFiles('/path/to/old/files', 30);
4. 将图像转换为 PDF
const fs = require('fs');
const PDFDocument = require('pdfkit');

function imagesToPDF(imageFolder, outputPDF) {
  const doc = new PDFDocument();
  const writeStream = fs.createWriteStream(outputPDF);
  doc.pipe(writeStream);
  fs.readdir(imageFolder, (err, files) => {
    if (err) throw err;
    files
      .filter((file) => /\.(jpg|jpeg|png)$/i.test(file))
      .forEach((file, index) => {
        const imagePath = `${imageFolder}/${file}`;
        if (index !== 0) doc.addPage();
        doc.image(imagePath, {
          fit: [500, 700],
          align: 'center',
          valign: 'center',
        });
      });
    doc.end();
    writeStream.on('finish', () => {
      console.log(`PDF created: ${outputPDF}`);
    });
  });
}
imagesToPDF('/path/to/images', 'output.pdf');
5. 自动文件备份
const fs = require('fs');
const path = require('path');

function backupFiles(sourceFolder, backupFolder) {
  fs.readdir(sourceFolder, (err, files) => {
    if (err) throw err;
    files.forEach((file) => {
      const sourcePath = path.join(sourceFolder, file);
      const backupPath = path.join(backupFolder, file);
      fs.copyFile(sourcePath, backupPath, (err) => {
        if (err) throw err;
        console.log(`Backed up ${file}`);
      });
    });
  });
}
const source = '/path/to/important/files';
const backup = '/path/to/backup/folder';
backupFiles(source, backup);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容