Node.js 教程
Node.js 基础
Node.js 概述
Node.js 环境搭建
Node.js 基础语法
Node.js 模块
Node.js 异步编程
Node.js 核心模块
Node.js文件系统
Node.js路径模块(path)
Node.js的HTTP模块
Node.js的url模块
Node.js流模块(stream)
Node.js 常用工具与框架
npm 与包管理
Express 框架
数据库操作
Socket.io 与 WebSocket
Node.js 实战项目
Web 应用开发
API 开发
爬虫应用
自动化脚本
Node.js部署与优化
部署 Node.js 应用
Node.js性能优化
Node.js应用的安全性
Node.js 高级话题
Node.js中的设计模式
TypeScript 与 Node.js
GraphQL 与 API 开发
-
+
首页
自动化脚本
一个使用 Node.js 开发的自动化脚本示例,包含文件操作、系统命令执行和定时任务功能。 ### **项目结构** ``` automation-script/ ├── lib/ │ ├── file-operations.js │ ├── system-commands.js │ └── scheduler.js ├── logs/ ├── config.json ├── package.json └── index.js ``` ### **1. 文件操作 (lib/file-operations.js)** ```javascript const fs = require('fs').promises; async function readFileSync(filePath) { try { const data = await fs.readFile(filePath, 'utf8'); console.log(`File "${filePath}" read successfully.`); return data; } catch (error) { console.error(`Error reading file "${filePath}":`, error.message); return null; } } async function writeFileSync(filePath, data) { try { await fs.writeFile(filePath, data); console.log(`Data written to file "${filePath}" successfully.`); return true; } catch (error) { console.error(`Error writing to file "${filePath}":`, error.message); return false; } } module.exports = { readFileSync, writeFileSync }; ``` ### **2. 系统命令执行 (lib/system-commands.js)** ```javascript const { exec } = require('child_process'); function executeCommand(command) { return new Promise((resolve, reject) => { exec(command, (error, stdout, stderr) => { if (error) { console.error(`Error executing command "${command}":`, error.message); reject(error); return; } console.log(`Command "${command}" executed successfully.`); resolve(stdout ? stdout : ''); }); }); } module.exports = { executeCommand }; ``` ### **3. 定时任务 (lib/scheduler.js)** ```javascript const cron = require('node-cron'); function scheduleTask(cronExpression, task) { cron.schedule(cronExpression, async () => { console.log(`Running scheduled task: ${new Date().toISOString()}`); await task(); }); } module.exports = { scheduleTask }; ``` ### **4. 配置文件 (config.json)** ```json { "inputFile": "data.txt", "outputFile": "processed_data.txt", "systemCommand": "echo 'Hello from Node.js!'", "cronExpression": "*/1 * * * * *" // 每分钟运行一次 } ``` ### **5. 主程序 (index.js)** ```javascript const path = require('path'); const fileOperations = require('./lib/file-operations'); const systemCommands = require('./lib/system-commands'); const scheduler = require('./lib/scheduler'); const config = require('./config.json'); async function processData() { // 读取文件 const inputFilePath = path.join(__dirname, config.inputFile); const data = await fileOperations.readFileSync(inputFilePath); // 处理数据 const processedData = data ? data.toUpperCase() : ''; // 写入文件 const outputFilePath = path.join(__dirname, config.outputFile); await fileOperations.writeFileSync(outputFilePath, processedData); // 执行系统命令 await systemCommands.executeCommand(config.systemCommand); console.log('Batch processing completed.'); } // 定时任务 scheduler.scheduleTask(config.cronExpression, processData); ``` ### **6. 依赖安装** ```bash npm install fs node-cron ``` ### **7. 运行脚本** ```bash node index.js ``` ### **功能说明** 1. **文件操作**: - 使用 `file-operations.js` 读取和写入文件。 - 通过 `path` 模块处理文件路径。 2. **系统命令执行**: - 使用 `child_process.exec` 执行系统命令。 - 命令输出和错误被捕获并记录。 3. **定时任务**: - 使用 `node-cron` 定义定时任务。 - 定时任务调用 `processData` 函数处理数据。 4. **配置管理**: - 使用 `config.json` 存储配置信息,如文件路径、系统命令和定时任务表达式。 5. **日志记录**: - 所有操作和任务执行情况都被记录到控制台。 ### **应用场景** - **数据处理**:定时从文件中读取数据,处理后写入新文件。 - **系统监控**:执行系统命令,监控系统状态或资源使用情况。 - **任务调度**:根据定时任务需求,定期执行特定任务。 通过以上代码,你可以构建一个强大的自动化脚本,用于处理文件、执行系统命令和调度任务。根据实际需求,可以进一步扩展功能,如添加错误处理、日志记录到文件、支持更多文件格式等。
wwbang
2025年2月27日 11:27
转发文档
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
Markdown文件
分享
链接
类型
密码
更新密码