Node+fs+定时器(node-schedule)+MySql

目标:将本人写博客时候的截图保存到桌面的图片  

执行保存到指定文件进行整理

并写入数据库

先看最终的目录结构:

package.json文件:

{
  "name": "zqz",
  "dependencies": {
    "mysql": "^2.10.2",
    "node-schedule": "^1.1.0"
  }
}

通过npm install node-schedule --save //--save的作用是将其加入package.json的dependencies(依赖项中)

2个依赖项:

node-schedule https://github.com/node-schedule/node-schedule 定时器

mysql https://github.com/felixge/node-mysql mysql

app.js文件:

var schedule = require(‘node-schedule‘);
var mysql = require(‘mysql‘);
var fs = require(‘fs‘);
const desktopPath = ‘C:/Users/Administrator/Desktop/‘;
const targetPath = ‘F://Blog_ScreenShot//‘;
const metaInfo = ‘blog‘;
var operationType = {
    0 : ‘插入‘,
    1 : ‘删除‘,
    2 : ‘修改‘,
    3 : ‘查询‘
}

/**
 * 轮询桌面
 * @return {[type]} [description]
 */
function timePoll(){
    console.log(‘--------[开始轮询]----------‘)
    schedule.scheduleJob(‘30 * * * * *‘, function(){
        visitDesk();
          console.log(‘每分钟的30s都会执行!:‘ + (new Date).toLocaleTimeString());
    });
}

/**
 * 访问桌面
 * @return {[type]} [description]
 */
function visitDesk(){
    console.log(‘--------开始访问桌面----------‘)
    fs.readdir(desktopPath,function(err, files){
       if (err) {
           return console.error(err);
       }

           files.forEach( function (file){
              if(file && judgeImage(file)){
                   saveImageToFile(file);
              }else{
                   console.log(‘桌面无资源!‘);
                   return;
              }

           });
    });
}

/**
 * 判断文件类型,取出我们需要的png图片
 * @return {[type]} [description]
 */
function judgeImage(file){
    var postfix = getPostfix(file);
    if(postfix === ‘png‘ && file.indexOf(metaInfo) > -1){
        return file;
    }
}

function getPostfix(file){
    var dotIndex = file.indexOf(‘.‘);
    var fileLen = file.length;
    return file.substring(dotIndex+1,fileLen);
}

/**
 * 将获取的图片存入
 * pipe,它以用来把当前的可读流和另外一个可写流连接起来。可读流中的数据会被自动写入到可写流中
 * @return {[type]} [description]
 */
function saveImageToFile(file){
    var fileReadStream = fs.createReadStream(desktopPath + file);
    var lastPath = targetPath + createDateFolder();
    if(!isFolderHave(lastPath)){
        createLastFloder(lastPath);
    }
    var fileWriteStream = fs.createWriteStream(lastPath + file);
    fileReadStream.pipe(fileWriteStream);
    fileWriteStream.on(‘close‘,function(){
          console.log(‘复制成功!‘);
          deleteDeskImage(file);
          //写入数据库
          connectMysql(file, lastPath, ‘0‘);
    })
}

/**
 * 删除桌面文件
 * @param  {[type]} file [description]
 * @return {[type]}      [description]
 */
function deleteDeskImage(file){
    fs.unlink(desktopPath + file, function(){
        console.log(‘删除成功!‘)
    })
}

/**
 * 以系统时间创建文件夹/年月日
 * @return {[type]} [description]
 */
function createDateFolder(){
    var day = (new Date).getDate();
    var month = (new Date).getMonth()+1;
    var year = (new Date).getFullYear();
    return year + ‘_‘ + month + ‘_‘ + day + ‘//‘;
}

/**
 * 判断文件夹是否存在
 * @return {[type]} [description]
 */
function isFolderHave(lastPath){
    fs.exists(lastPath, function(exists){
        if(exists){
            return true;
        }else{
            return false;
        }
    })
}

/**
 * 创建最终目标文件夹
 * @param  {[type]} lastPath [description]
 * @return {[type]}          [description]
 */
function createLastFloder(lastPath){
    fs.mkdir( lastPath, function(){
        console.log(‘[文件夹创建]-‘ +lastPath + "成功!");
    })
}

/**
 * 连接数据库
 * @return {[type]} [description]
 */
function connectMysql(picname, picurl, time){
    var connection = mysql.createConnection({
      host     : ‘localhost‘,
      user     : ‘root‘,
      password : ‘root‘,
      database : ‘nodejs‘
    });

    connection.connect(function(err){
        if(err){
            console.log(err);
            return;
        }
        console.log(‘连接成功!‘);
    });

    saveToDataBase(connection, picname, picurl);

    connection.end(function(err){
        if(err){
            return;
        }
        console.log(‘关闭连接成功!‘);
    });
}

/**
 * 将数据存入数据库,进行持久化
 * @return {[type]} [description]
 */
function saveToDataBase( connection, picname, picurl){
    var  querySql = ‘INSERT INTO scaingDeskImg(Id,picname,picurl,time) VALUES(0,?,?,?)‘;

    //注意存入数据库中的数据如果有中文会出现,乱码错误,导致执行失败!
    var  querySql_Params = [picname, targetPath+picurl+picname, new Date];

    operationDataBase( connection,querySql, querySql_Params, operationType[‘0‘]);
}

/**
 * 对数据库的操作
 * @return {[type]} [description]
 */
function operationDataBase( connection, querySql, querySql_Params,flag){
    connection.query( querySql, querySql_Params, function (err, result) {
        if(err){
         console.log(‘[‘ + flag + ‘ERROR] - ‘,err.message);
         return;
        }        

       console.log(flag + ‘成功!‘);
    });
}

timePoll();

结果:

涉及的知识:

 定时器:

schedule.scheduleJob(‘30 * * * * *‘, function(){
    visitDesk();
      console.log(‘每分钟的30s都会执行!:‘ + (new Date).toLocaleTimeString());
}); 

定时器中的第一个参数:

 秒  分   时    日   月    周 

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    |
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)

例如:

30 * * * * * 就表示每分钟的30秒执行

30 2 * * * * 就表示每小时的2分30秒执行

30 2 21 * * * 就表示每天的21点2分30秒执行

30 2 21 8 * * 就表示每月的8号21点2分30秒执行

...依次类推

读写文件:

//从桌面将文件读入流

var fileReadStream = fs.createReadStream(desktopPath + file);

//从要存入的文件创建写入流

var fileWriteStream = fs.createWriteStream(lastPath + file);

//最后通过node的pipe()的方法连接两个数据流,犹如管道一样将数据读入写入

  fileReadStream.pipe(fileWriteStream);

具体的可以参见API。

时间: 2024-08-03 20:51:28

Node+fs+定时器(node-schedule)+MySql的相关文章

paip.最好的脚本语言node js 环境搭建连接mysql

6.4 一些说明 数据属性可以重写同名的方法属性.这是为了避免在大型系统中产生问题的意外名称冲突.所以用一些减少冲突的常用方法是很有效果的.常用的方法包括:大写字母方法名称,用唯一的字符串来做为数据属性的名称(可以是个下划线_)或者用动词命名方法和用名字命名数据属性. 数据属性就像和对象的普通用户一样可以被方法引用.换句话说,类不能用来实现纯净的数据类型.事实上,在python中不能强制数据隐藏,一切基于约定.(另一方面,如C中写的,python的实现可以做到完全隐藏实现细节并且在必要是可以控制

node.js cannot find module 'mysql'

nodejs cannot find module 'mysql' 问题分析 在windows平台下,测试nodejs连接mysql数据库. 首先 在控制台中安装mysql依赖包 一开始我是在相应js所在在目录下安装mysql支持,结果是: 看到那么多WARN时,以为自己装的有问题,于是准备进行全局安装, npm install -g mysql 并没有error和warn. 但是当执行js时,会抛出异常 原因是:安装成功后,mysql依赖包在C:\Users\陈\AppData\Roaming

Solve Error: node postinstall sh: node: command not found

When install the yeoman using the following command: npm install -g yo You might have the following error: npm WARN deprecated [email protected]2.2.5: cross-spawn no longer requires a build toolchain, use it instead /root/.nvm/versions/node/v9.3.0/bi

hidden node and exposed node problem

Exposed node problem In wireless networks, theexposed node problem occurs when a node is prevented from sending packets to other nodes because of a neighboring transmitter. Consider an example of 4 nodes labeled R1, S1, S2, and R2, where the two rece

001 -- Circle LinkList, list initiate, add a new node, delete a node, and List traverse

#include <studio.h> #include <stdlib.h> typedef struct CLinkList { int data; struct CLinkList *next ; } node; /*initiate a circle list*/ void ds_init(node **pNode) { int item; node *temp; node *target; printf("please input the value of th

Elasticsearch master node、 data node、 client node的区别与各自特点

es集群里的master node.data node和client node到底是怎么个意思,分别有何特点? master节点 主要功能是维护元数据,管理集群各个节点的状态,数据的导入和查询都不会走master节点,所以master节点的压力相对较小,因此master节点的内存分配也可以相对少些:但是master节点是最重要的,如果master节点挂了或者发生脑裂了,你的元数据就会发生混乱,那样你集群里的全部数据可能会发生丢失,所以一定要保证master节点的稳定性. data node 是负

.NET程序员也学Node.js——初识Node.js

清明在石门休了八天假,一眨眼,4月又到中旬了...看到.NET在天朝彻底沦陷而又无能为力,我开始尝试去学习一些新的东西来充实自己,我自然是打死不会去学java的,没有为什么,于是乎,最近开始学习一些前端的开发技术,就让学习笔记来记录一下我的学习历程并同大家一起分享吧! 申明:我只是业余学着好玩的,顺便扩展一下视野,各位广大.NET同行不要被我带沟里去了,当然如果你想从事移动前端或者全栈开发的话还是有必要学习一下的. Node.js简介 Node.js 的推出,不仅从工程化的角度自动化掉更多琐碎费

JavaScript - Node.children和Node.childNodes的区别

写到这个也是因为群里的学长面试的时候遇到了这个问题,然后顺手分享了一下 首先是MDN里面对两个API的解释 children Node.children is a read-only property that returns a live HTMLCollection of the child elements of Node. childNodes The Node.childNodes read-only property returns a live collection of chil

cocos2dx基础篇(8)——定时器更新schedule、update

[本节内容] 定时器在大部分游戏中是不可或缺的,即每隔一段时间,就要执行相应的刷新体函数,以更新游戏的画面.时间.进度.敌人的指令等等. cocos2dx为我们提供了定时器schedule相关的操作.其操作函数的定义在CCNode中,所以基本上大多数的引擎类都可以设置定时器,如CCLayer.CCSprite.CCMenu等. 定时器更新的方式分为三类: (1)默认定时器:scheduleUpdate(); (2)自定义定时器:schedule(); (3)一次性定时器:scheduleOnce