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

11個(gè)JavaScript中自動(dòng)化執(zhí)行日常工作的殺手腳本

 更新時(shí)間:2025年06月06日 08:28:01   作者:程序員成長(zhǎng)指北  
這篇文章主要來和大家分享?11?個(gè)?JavaScript?腳本,它們可以幫助您自動(dòng)化日常工作的各個(gè)方面,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下

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)控開發(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ò)過任何約會(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ì)刪除超過 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. 在語言之間翻譯文本文件

需要快速翻譯文本文件?此腳本使用 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,對(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ù)

通過從天氣 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 注冊(cè)一個(gè)免費(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個(gè)JavaScript中自動(dòng)化執(zhí)行日常工作的殺手腳本的文章就介紹到這了,更多相關(guān)JavaScript自動(dòng)化腳本內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

重庆市| 镶黄旗| 无棣县| 博爱县| 南丹县| 衡南县| 亳州市| 岱山县| 连平县| 嘉祥县| 城口县| 叶城县| 平湖市| 六枝特区| 赣州市| 永新县| 上杭县| 嘉定区| 桑植县| 淮安市| 东兴市| 南丹县| 扬州市| 上虞市| 屏东县| 施秉县| 凤台县| 柞水县| 平乡县| 肥西县| 寻乌县| 阿克陶县| 都兰县| 龙游县| 南丰县| 桂阳县| 宜川县| 聊城市| 东兴市| 射洪县| 修文县|