欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2025年05月12日 09:53:55   作者:獨(dú)立開閥者_(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è)運(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 nowconst 
    futureTime = Date.now() + 10000;
    sendScheduledEmail('recipient@example.com', 'Hello!', 'This is a scheduled email.', futureTime);

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

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

是否曾經(jīng)想跟蹤文件的歷史記錄。這可以幫助您實(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)控開發(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,對于小型項(xiàng)目是免費(fèi)的。

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 注冊一個免費(fèi)的 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)文章

  • JavaScript前后端數(shù)據(jù)交互工具ajax使用教程

    JavaScript前后端數(shù)據(jù)交互工具ajax使用教程

    Ajax(Asynchronous?Javascript?And?XML),即是異步的JavaScript和XML,Ajax其實(shí)就是瀏覽器與服務(wù)器之間的一種異步通信方式
    2022-10-10
  • JavaScript中.min.js和.js文件的區(qū)別講解

    JavaScript中.min.js和.js文件的區(qū)別講解

    今天小編就為大家分享一篇關(guān)于JavaScript中.min.js和.js文件的區(qū)別講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-02-02
  • 微信小程序?qū)崿F(xiàn)監(jiān)聽頁面滾動

    微信小程序?qū)崿F(xiàn)監(jiān)聽頁面滾動

    這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)監(jiān)聽頁面滾動,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-06-06
  • JS實(shí)現(xiàn)給對象動態(tài)添加屬性的方法

    JS實(shí)現(xiàn)給對象動態(tài)添加屬性的方法

    這篇文章主要介紹了JS實(shí)現(xiàn)給對象動態(tài)添加屬性的方法,涉及JS屬性的遍歷、動態(tài)賦值及eval方法的簡單使用技巧,需要的朋友可以參考下
    2017-01-01
  • JS+HTML5 FileReader對象用法示例

    JS+HTML5 FileReader對象用法示例

    這篇文章主要介紹了JS+HTML5 FileReader對象用法,結(jié)合具體實(shí)例形式分析了FileReader對象的常用方法及簡單使用技巧,需要的朋友可以參考下
    2017-04-04
  • 當(dāng)前流行的JavaScript代碼風(fēng)格指南

    當(dāng)前流行的JavaScript代碼風(fēng)格指南

    這篇文章主要介紹了當(dāng)前流行的JavaScript代碼風(fēng)格指南,同時推薦了一款風(fēng)格檢驗(yàn)工具jshint,可以配合大多數(shù)的編輯器統(tǒng)一團(tuán)隊代碼風(fēng)格,需要的朋友可以參考下
    2014-09-09
  • JS實(shí)現(xiàn)的拋物線運(yùn)動效果示例

    JS實(shí)現(xiàn)的拋物線運(yùn)動效果示例

    這篇文章主要介紹了JS實(shí)現(xiàn)的拋物線運(yùn)動效果,結(jié)合實(shí)例形式分析了javascript拋物線運(yùn)動的相關(guān)運(yùn)算與元素動態(tài)操作實(shí)現(xiàn)技巧,需要的朋友可以參考下
    2018-01-01
  • 微信小程序?qū)崿F(xiàn)軌跡回放的示例代碼

    微信小程序?qū)崿F(xiàn)軌跡回放的示例代碼

    這篇文章主要介紹了微信小程序?qū)崿F(xiàn)軌跡回放的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • 微信小程序遍歷Echarts圖表實(shí)現(xiàn)多個餅圖

    微信小程序遍歷Echarts圖表實(shí)現(xiàn)多個餅圖

    這篇文章主要介紹了微信小程序遍歷Echarts圖表實(shí)現(xiàn)多個餅圖,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • 怎么清空javascript數(shù)組

    怎么清空javascript數(shù)組

    這是一個很基礎(chǔ)的問題,但是我們往往經(jīng)常做錯,這里簡單分享下,方便需要的朋友
    2013-05-05

最新評論