11 個(gè) JavaScript 殺手腳本,用于自動(dòng)執(zhí)行日常任務(wù)
今天這篇文章,我將分享我使用收藏的 11 個(gè) JavaScript 腳本,它們可以幫助您自動(dòng)化日常工作的各個(gè)方面。
1. 自動(dòng)文件備份
擔(dān)心丟失重要文件?此腳本將文件從一個(gè)目錄復(fù)制到備份文件夾,確保您始終保存最新版本。
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 作業(yè)運(yùn)行
2. 發(fā)送預(yù)定電子郵件
需要稍后發(fā)送電子郵件但又擔(dān)心忘記?此腳本允許您使用 Node.js 安排電子郵件。
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);
注意:傳遞您自己的憑據(jù)
3. 監(jiān)控目錄的更改
是否曾經(jīng)想跟蹤文件的歷史記錄。這可以幫助您實(shí)時(shí)跟蹤它。
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');
用例:非常適合關(guān)注共享文件夾或監(jiān)控開(kāi)發(fā)目錄中的變化。
4. 將圖像轉(zhuǎn)換為 PDF
需要將多幅圖像編譯成一個(gè) PDF?此腳本使用 pdfkit 庫(kù)即可完成此操作。
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');
提示:非常適合編輯掃描文檔或創(chuàng)建相冊(cè)。
5. 桌面通知提醒
再也不會(huì)錯(cuò)過(guò)任何約會(huì)。此腳本會(huì)在指定時(shí)間向您發(fā)送桌面通知。
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. 自動(dòng)清理舊文件
此腳本會(huì)刪除超過(guò) n 天的文件。
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);
警告:請(qǐng)務(wù)必仔細(xì)檢查文件夾路徑,以避免刪除重要文件。
7. 在語(yǔ)言之間翻譯文本文件
需要快速翻譯文本文件?此腳本使用 API 在語(yǔ)言之間翻譯文件。
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,對(duì)于小型項(xiàng)目是免費(fèi)的。
8. 將多個(gè) PDF 合并為一個(gè)
輕松將多個(gè) PDF 文檔合并為一個(gè)文件。
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');
應(yīng)用程序:用于將報(bào)告、發(fā)票或任何您想要的 PDF 合并到一個(gè)地方。
9. 批量重命名文件
需要重命名一批文件嗎?此腳本根據(jù)模式重命名文件。
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') 函數(shù)用零填充數(shù)字(例如,001,002),這有助于排序。
10. 抓取天氣數(shù)據(jù)
通過(guò)從天氣 API 抓取數(shù)據(jù)來(lái)了解最新天氣情況。
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 注冊(cè)一個(gè)免費(fèi)的 API 密鑰。
11. 生成隨機(jī)引語(yǔ)
此腳本獲取并顯示隨機(jī)引語(yǔ)。
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();
最后,感謝您一直閱讀到最后!希望今天內(nèi)容能夠幫助到你,如果你喜歡此內(nèi)容的話,也請(qǐng)分享給你的小伙伴,也許能夠幫助到他們。