# JavaScript的11個實用Scripts腳本
本篇文章屬於翻譯內容,因為還滿實用的,介紹並分享給大家
## 1. Automated File Backup 自動文件備份
將檔案從一個目錄複製到備份資料夾,保存最新版本。
```javascript!
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);
```
提示: 使用cron進行排程備份
## Send Scheduled Emails 發送預定電子郵件
使用 Node.js 排程發送電子郵件。
```javascript!
const nodemailer = require('nodemailer');
function sendScheduledEmail(toEmail, subject, body, sendTime) {
const delay = sendTime - Date.now();
setTimeout(() => {
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your_email@gmail.com',
pass: 'your_password', // Consider using environment variables for security
},
});
let mailOptions = {
from: 'your_email@gmail.com',
to: toEmail,
subject: subject,
text: body,
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}, delay);
}
// Schedule email for 10 seconds from now
const futureTime = Date.now() + 10000;
sendScheduledEmail('recipient@example.com', 'Hello!', 'This is a scheduled email.', futureTime);
```
## 3. Monitor Directory for Changes監控目錄變更
監控目錄變更的歷史記錄。
```javascript!
const fs = require('fs');
function monitorFolder(pathToWatch) {
fs.watch(pathToWatch, (eventType, filename) => {
if (filename) {
console.log(`${eventType} on file: ${filename}`);
} else {
console.log('filename not provided');
}
});
}
monitorFolder('/path/to/watch');
```
## 4. Convert Images to PDF 圖檔轉換為 PDF
將多張圖片編譯成一個 PDF?此腳本使用 pdfkit 套件。
```javascript!
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');
```
提示: 非常適合編譯掃描的文件或創建相冊。
注意: 您需要先安裝此套件:npm install pdfkit。
## 5. Desktop Notifications for Reminders提醒的桌面通知
指定時間發送桌面通知。
```typescript
const notifier = require('node-notifier');
function desktopNotifier(title, message, notificationTime) {
const delay = notificationTime - Date.now();
setTimeout(() => {
notifier.notify({
title: title,
message: message,
sound: true, // Only Notification Center or Windows Toasters
});
console.log('Notification sent!');
}, delay);
}
// Notify after 15 seconds
const futureTime = Date.now() + 15000;
desktopNotifier('Meeting Reminder', 'Team meeting at 3 PM.', futureTime);
```
注意: 您需要先安裝此套件:npm install node-notifier。
## 6. Clean Up Old Files Automatically自動清理舊檔
此script將刪除超過 n 天的檔案。
```typescript
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);
```
謹慎: 請務必仔細檢查資料夾路徑,以避免刪除重要檔。
## 7. Translate Text Files Between Languages語言之間翻譯文字檔
快速翻譯文本檔?此文稿使用 API 在語言之間翻譯檔。
```typescript
const fs = require('fs');
const axios = require('axios');
async function translateText(text, targetLanguage) {
const response = await axios.post('https://libretranslate.de/translate', {
q: text,
source: 'en',
target: targetLanguage,
format: 'text',
});
return response.data.translatedText;
}
(async () => {
const originalText = fs.readFileSync('original.txt', 'utf8');
const translatedText = await translateText(originalText, 'es');
fs.writeFileSync('translated.txt', translatedText);
console.log('Translation completed.');
})();
```
注意: 這使用 LibreTranslate API,該 API 對小型專案是免費的。
## Merge Multiple PDFs into One將多個 PDF 合併為一個
將多個 PDF 合併為一個
```typescript
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');
```
應用: 用於將報告、發票或您想要的任何 PDF 合併到一個位置。
注意: 您需要先安裝此套件:npm install pdf-merger-js。
## 9. Batch Rename Files批量重新命名檔
重新命名一批檔?此文稿根據模式重新命名檔
```typescript
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');
```
提示:padStart(3, '0') 函數用 0 填充數值(例如 001, 002)來作為排序。
## 10. Scrape Weather Data 抓取天氣數據
透過 weather API 抓取數據,隨時更新最新的天氣資訊。
```typescript
const axios = require('axios');
async function getWeather(city) {
const apiKey = 'your_openweathermap_api_key';
const response = await axios.get(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`
);
const data = response.data;
console.log(`Current weather in ${city}: ${data.weather[0].description}, ${data.main.temp}°C`);
}
getWeather('New York');
```
注意: 您需要在 OpenWeatherMap 上註冊免費的 API 金鑰。
每天前 1000 次 API 呼叫免費,超過就要$$了
## 11. Generate Random Quotes隨機獲取資料。
程式需要灌入測試資料時,就可以用quotable的API來產生
```typescript
const axios = require('axios');
async function getRandomQuote() {
const response = await axios.get('https://api.quotable.io/random');
const data = response.data;
console.log(`"${data.content}" \n- ${data.author}`);
}
getRandomQuote();
```
>出處來源
>https://medium.com/@yashwanthnandam/11-javascript-killer-scripts-to-automate-daily-tasks-e2178ee6ede4
>