2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!

Fork me on GitHub

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。

 

posted on 2016-05-13 22:20  qize  阅读(1437)  评论(0编辑  收藏  举报

导航