一个处理文件的脚本

/*
* @Author: yangyuxuan wuqi_y@163.com
* @Date: 2025-02-18 10:24:47
* @LastEditors: yangyuxuan wuqi_y@163.com
* @LastEditTime: 2025-02-18 15:55:32
* @Description:node脚本-重命名-移动目录
*
*/
const fs = require('fs');
const path = require('path');

// 定義文件的路徑
const distDir = path.resolve('./dist');
const oldFile = path.join(distDir, 'index.html');
const newFile = path.join(distDir, 'index.html');

const sourceDir = path.resolve('./dist/assets');
const targetDir = path.resolve('../../../../public/static/wps_app_assets/assets');

// 檢查文件是否存在並重命名
if (fs.existsSync(oldFile)) {
fs.rename(oldFile, newFile, (err) => {
if (err) {
console.error('Error renaming file:', err);
} else {
console.log('index.html has been renamed to index.html');
}
});
} else {
console.error('index.html does not exist.');
}

// 移动
// 確保目標目錄存在,如果不存在則創建
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir, { recursive: true });
} else {
// 先清空targetDir目录
fs.readdir(targetDir, (err, files) => {
if (err) throw err;
files.forEach(file => {
const filePath = path.join(targetDir, file);
fs.unlink(filePath, (err) => {
if (err) throw err;
console.log(`Deleted: ${filePath}`);
});
});
});
}
// 移動文件的函數
function moveFile (source, target) {
fs.rename(source, target, (err) => {
if (err) throw err;
console.log(`Moved: ${source} -> ${target}`);
});
}

// 遍歷 dist 目錄中的文件,並移動到 output 目錄
fs.readdir(sourceDir, (err, files) => {
if (err) throw err;

files.forEach(file => {
const sourceFile = path.join(sourceDir, file);
const targetFile = path.join(targetDir, file);
moveFile(sourceFile, targetFile);
});
});