最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

11個JavaScript自動執(zhí)行日常任務(wù)的腳本分析

 更新時間:2025年05月12日 09:53:55   作者:獨立開閥者_(dá)FwtCoder  
這篇文章主要和大家分享?11?個?JavaScript?腳本,它們可以幫助您自動化日常工作的各個方面,文中的示例代碼講解詳細(xì),有需要的小伙伴可以了解下

1. 自動文件備份

擔(dān)心丟失重要文件?此腳本將文件從一個目錄復(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è)運行

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 nowconst 
    futureTime = Date.now() + 10000;
    sendScheduledEmail('recipient@example.com', 'Hello!', 'This is a scheduled email.', futureTime);

注意:傳遞您自己的憑據(jù)

3. 監(jiān)控目錄的更改

是否曾經(jīng)想跟蹤文件的歷史記錄。這可以幫助您實時跟蹤它。

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)控開發(fā)目錄中的變化。

4. 將圖像轉(zhuǎn)換為 PDF

需要將多幅圖像編譯成一個 PDF?此腳本使用 pdfkit 庫即可完成此操作。

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)建相冊。

5. 桌面通知提醒

再也不會錯過任何約會。此腳本會在指定時間向您發(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 secondsconst 
    futureTime = Date.now() + 15000;
    desktopNotifier('Meeting Reminder', 'Team meeting at 3 PM.', futureTime);

注意:您需要先安裝此包:npm install node-notifier。

6. 自動清理舊文件

此腳本會刪除超過 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);

警告:請務(wù)必仔細(xì)檢查文件夾路徑,以避免刪除重要文件。

7. 在語言之間翻譯文本文件

需要快速翻譯文本文件?此腳本使用 API 在語言之間翻譯文件。

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,對于小型項目是免費的。

8. 將多個 PDF 合并為一個

輕松將多個 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');

應(yīng)用程序:用于將報告、發(fā)票或任何您想要的 PDF 合并到一個地方。

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ù)

通過從天氣 API 抓取數(shù)據(jù)來了解最新天氣情況。

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 密鑰。

11. 生成隨機(jī)引語

此腳本獲取并顯示隨機(jī)引語。

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();

到此這篇關(guān)于11個JavaScript自動執(zhí)行日常任務(wù)的腳本分析的文章就介紹到這了,更多相關(guān)JavaScript自動執(zhí)行腳本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

班戈县| 习水县| 南投市| 湾仔区| 盐池县| 黑河市| 无为县| 天门市| 玉龙| 彰化县| 宽甸| 三穗县| 罗甸县| 中方县| 长汀县| 阜平县| 兴化市| 柳江县| 连城县| 双辽市| 陇西县| 莎车县| 顺平县| 祁东县| 桦南县| 那曲县| 常德市| 庄浪县| 兴化市| 安仁县| 两当县| 喀喇沁旗| 大英县| 正镶白旗| 元朗区| 建德市| 荔浦县| 青海省| 辽阳县| 洞头县| 郓城县|