自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

11 個(gè) JavaScript 殺手腳本,用于自動(dòng)執(zhí)行日常任務(wù)

開(kāi)發(fā) 前端
今天這篇文章,我將分享我使用收藏的 11 個(gè) JavaScript 腳本,它們可以幫助您自動(dòng)化日常工作的各個(gè)方面。

今天這篇文章,我將分享我使用收藏的 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)分享給你的小伙伴,也許能夠幫助到他們。

責(zé)任編輯:華軒 來(lái)源: web前端開(kāi)發(fā)
相關(guān)推薦

2024-08-14 14:42:00

2024-07-01 18:07:30

Python腳本自動(dòng)化

2022-10-09 14:50:44

Python腳本

2024-09-23 17:00:00

Python編程

2022-07-06 08:39:33

Python代碼

2022-10-20 15:16:23

JavaScript數(shù)組技能

2021-04-01 06:13:50

Ansible系統(tǒng)運(yùn)維

2023-11-10 09:32:23

Python文件操作

2021-01-27 07:56:04

Python編程語(yǔ)言

2025-02-07 12:58:33

python自動(dòng)化腳本

2024-06-17 10:34:12

2024-12-10 00:01:00

自動(dòng)化腳本優(yōu)化

2024-06-21 10:46:44

2019-12-04 15:08:04

AWS亞馬遜機(jī)器學(xué)習(xí)

2023-06-14 15:51:48

JavaScript

2021-11-22 10:40:35

Linux腳本內(nèi)存

2023-06-05 11:51:47

機(jī)器學(xué)習(xí)數(shù)據(jù)源

2022-11-28 23:44:26

JavaScript技巧程序員

2013-07-04 13:37:23

Java開(kāi)發(fā)速度

2024-08-02 17:19:36

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)