Goal: To write my blog when the save to the desktop picture
Execute save to the specified file for collation
and write to the database
Let's look at the final directory structure:
Package.json file:
{ "name": "Zqz", "dependencies": { "mysql": "^2.10.2", "Node-schedule": "^1.1.0" }}
The role of Node-schedule--save//--save via NPM install is to add it to Package.json dependencies (dependencies)
2 dependencies:
Node-schedule Https://github.com/node-schedule/node-schedule Timer
MySQL https://github.com/felixge/node-mysql MySQL
app.js file :
varSchedule = require (' Node-schedule '));varMySQL = require (' MySQL ');varFS = require (' FS '); Const DesktopPath= ' c:/users/administrator/desktop/'; Const TargetPath= ' f://blog_screenshot//'; Const MetaInfo= ' Blog ';varOperationtype = { 0: ' Insert ', 1: ' Delete ', 2: ' Modify ', 3: ' Query '}/** Poll Desktop * @return {[type]} [description]*/functionTimepoll () {Console.log ('--------[start polling]----------') Schedule.schedulejob (' 30 * * * * * ',function() {visitdesk (); Console.log (' 30s per minute will execute!: ' + (NewDate). tolocaletimestring ()); }); }/** * Access Desktop * @return {[type]} [description]*/functionVisitdesk () {Console.log ('--------start accessing the desktop----------') Fs.readdir (DesktopPath,function(err, files) {if(err) {returnConsole.error (ERR); } Files.foreach (function(file) {if(File &&judgeimage (file)) {saveimagetofile (file); }Else{Console.log (' Desktop No resources! '); return; } }); });}/** * Determine file type, take out the PNG image we need * @return {[type]} [description]*/functionjudgeimage (file) {varPostfix =getpostfix (file); if(Postfix = = = ' png ' && file.indexof (metainfo) >-1){ returnfile; }}functionGetpostfix (file) {varDotindex = File.indexof ('. ')); varFileLen =file.length; returnFile.substring (dotindex+1, FileLen);}/** * The captured image is deposited into the pipe, which is used to connect the current readable stream with another writable stream. Data in the readable stream is automatically written to the writable stream * @return {[type]} [description]*/functionsaveimagetofile (file) {varFilereadstream = Fs.createreadstream (DesktopPath +file); varLastpath = TargetPath +Createdatefolder (); if(!Isfolderhave (Lastpath)) {Createlastfloder (Lastpath); } varFilewritestream = Fs.createwritestream (Lastpath +file); Filereadstream.pipe (Filewritestream); Filewritestream.on (' Close ',function() {Console.log (' Copy succeeded! '); Deletedeskimage (file); //Write to DatabaseConnectmysql (file, Lastpath, ' 0 '); })}/** * Delete Desktop file * @param {[type]} file [description] * @return {[type]} [description]*/functiondeletedeskimage (file) {Fs.unlink (DesktopPath+ File,function() {Console.log (' Delete succeeded! ') })}/** * Create folder in system time/month Day * @return {[type]} [description]*/functionCreatedatefolder () {varDay = (NewDate). GetDate (); varMonth = (NewDate). GetMonth () +1; varYear = (NewDate). getFullYear (); returnYear + ' _ ' + month + ' _ ' + day + '//';}/** * To determine if a folder exists * @return {[type]} [description]*/functionIsfolderhave (Lastpath) {fs.exists (Lastpath,function(exists) {if(exists) {return true; }Else{ return false; } })}/** * Create Final Destination folder * @param {[type]} Lastpath [description] * @return {[type]} [description]*/functionCreatelastfloder (Lastpath) {Fs.mkdir (Lastpath,function() {Console.log (' [Folder creation]-' +lastpath + ' success! '); })}/** * Connect to Database * @return {[type]} [description]*/functionConnectmysql (Picname, Picurl, time) {varConnection =mysql.createconnection ({host:' localhost ', User:' Root ', Password:' Root ', Database:' Nodejs ' }); Connection.connect (function(err) {if(Err) {Console.log (err); return; } console.log (' Connected successfully! '); }); Savetodatabase (Connection, Picname, Picurl); Connection.end (function(err) {if(err) {return; } console.log (' Close connection succeeded! '); });}/** * data is stored in the database for persistence * @return {[type]} [description]*/functionsavetodatabase (Connection, Picname, Picurl) {varQuerysql = ' INSERT into scaingdeskimg (id,picname,picurl,time) VALUES (0,?,?,?) '; //Note the data stored in the database if there is a Chinese will appear, garbled error, resulting in execution failure! varQuerysql_params = [Picname, Targetpath+picurl+picname,NewDate]; Operationdatabase (Connection,querysql, Querysql_params, operationtype[' 0 ']);}/** * operation on Database * @return {[type]} [description]*/functionoperationdatabase (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+ ' success! '); });} Timepoll ();
Results :
The knowledge involved:
Timer:
function () { visitdesk (); Console.log (' 30s per minute will execute!: ' + (new
The first parameter in a timer:
Second-time time-sharing week
* * * * * *┬ ┬ ┬ ┬ ┬ ┬│ │ │ │ │ |│ │ │ │ │ └ 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)
For example:
30 * * * * * represents 30 seconds per minute of execution
30 2 * * * means 2 minutes and 30 seconds per hour execution
30 2 21 * * means 21 points per day 2 minutes 30 seconds to execute
30 2 21 8 * * means 8th 21 points 2 minutes 30 seconds per month
... In turn
Read and Write files:
Read a file from the desktop to the stream
var filereadstream = fs.createreadstream (desktoppath + file);
Create a write stream from the file to be deposited
var filewritestream = fs.createwritestream (lastpath + file);
Finally, through node's pipe () method to connect two data streams, like a pipeline to read data into the Write
Filereadstream.pipe (Filewritestream);
Refer to the API for details.
node+fs+ timer (node-schedule) +mysql