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。
Node+fs+定时器(node-schedule)+MySql的更多相关文章
- paip.最好的脚本语言node js 环境搭建连接mysql
paip.最好的脚本语言node js 环境搭建连接mysql #====下载node...走十一个exe..容易的.. 1 #0----Hello world .js 2 #---------模 ...
- 解决node fs.writeFile 生成csv 文件乱码问题
解决node fs.writeFile 生成csv 文件乱码问题: fs.writeFile('xxx.csv', '\ufeff' + 要传入的数据, {encoding: 'utf8'}); \u ...
- 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 ...
- 一起来学node.js吧 node school简介
node.js这几年火爆的简直丧心病狂,去lagou.com查查node.js的职位,那叫一个多. 要说火爆到什么程度,竟然有一个网站专门去教大家学习node.js, Node School. 进去逛 ...
- 获取所有树叶子节点 注册添加事件 if ($(node).tree('isLeaf', node.target)) 是否叶子节点
//获取所有树叶子节点 注册添加事件 if ($(node).tree('isLeaf', node.target)) 是否叶子节点 $(function () { $('.easyui-tree') ...
- .NET程序员也学Node.js——初识Node.js
清明在石门休了八天假,一眨眼,4月又到中旬了...看到.NET在天朝彻底沦陷而又无能为力,我开始尝试去学习一些新的东西来充实自己,我自然是打死不会去学java的,没有为什么,于是乎,最近开始学习一些前 ...
- node基础篇一:node介绍、node http、node event 课堂(持续)
最近工作一直很忙,没时间更新,谅解,这次准备更新一次node教程,本课堂将持续更新,每周坚持更新一到两章,希望对大家有一些小帮助吧: 一.首先什么是node? 1/Node.js 是一个基于 Chro ...
- elasticsearch节点(角色)类型解释node.master和node.data
在生产环境下,如果不修改elasticsearch节点的角色信息,在高数据量,高并发的场景下集群容易出现脑裂等问题. 默认情况下,elasticsearch集群中每个节点都有成为主节点的资格,也都存储 ...
- elasticsearch负载均衡节点——客户端节点 node.master: false node.data: false 其他配置和master 数据节点一样
elasticSearch的配置文件中有2个参数:node.master和node.data.这两个参 数搭配使用时,能够帮助提供服务器性能. 数据节点node.master: false node. ...
随机推荐
- C++内存对齐总结
大家都知道,C++空类的内存大小为1字节,为了保证其对象拥有彼此独立的内存地址.非空类的大小与类中非静态成员变量和虚函数表的多少有关. 而值得注意的是,类中非静态成员变量的大小与编译器内存对齐的设置有 ...
- HTML5 progress和meter控件
在HTML5中,新增了progress和meter控件.progress控件为进度条控件,可表示任务的进度,如Windows系统中软件的安装.文件的复制等场景的进度.meter控件为计量条控件,表示某 ...
- C#多线程之基础篇3
在上一篇C#多线程之基础篇2中,我们主要讲述了确定线程的状态.线程优先级.前台线程和后台线程以及向线程传递参数的知识,在这一篇中我们将讲述如何使用C#的lock关键字锁定线程.使用Monitor锁定线 ...
- JQuery 选择器
选择器是JQuery的根基,在JQuery中,对事件的处理,遍历DOM和AJAX操作都依赖于选择器.如果能够熟练地使用选择器,不仅能简化代码,而且还可以事半功倍. JQuery选择器的优势 1.简洁的 ...
- css3线条围绕跑马+jquery打字机效果
原文地址:css3线条围绕跑马+jquery打字机效果 有图有真相,今天偶然看到了一种效果,仔细看了下,发现它是用css的clip+css3的动画实现的,简直叼.于是自己拿来了前一阵子写的打字机效果, ...
- ASP.NET MVC——模型绑定
这篇文章我们来讲讲模型绑定(Model Binding),其实在初步了解ASP.NET MVC之后,大家可能都会产生一个疑问,为什么URL片段最后会转换为例如int型或者其他类型的参数呢?这里就不得不 ...
- [修正] Firemonkey TFrame 存档后,下次载入某些事件连结会消失(但源码还在)
问题:Firemonkey TFrame 存档后,下次载入某些事件连结会消失(但源码还在) 解决:(暂时方法) type TTestFrame = class(TFrame) public const ...
- 浏览器的兼容模式下的button中文字垂直方向不居中显示
<button style="cursor:pointer;vertical-align: middle;" >删除</button> 这时候垂直不居中. ...
- Linux基础介绍【第五篇】
linux权限位 Linux文件或目录的权限位是由9个权限位来控制,每三位为一组,它们分别是文件属主权限.属组权限.其他用户权限. r:read可读权限,对应数字4: w:write可写权限,对应数字 ...
- PHP5.4~7.1新特性总结
http://note.youdao.com/noteshare?id=7273b858fc12873ad092979e4ba173a7&sub=WEB334fdcf50b507ad93549 ...