标签:
3.格式化时间
promise.js
/* 工具类 2016年8月22日09:07:50 */ var db = {}; var mysql = require('mysql'); var nodemailer = require('nodemailer'); var pool = mysql.createPool({ connectionLimit : 10, host : 'localhost', user : 'root', password : '123456', database : 'nodejs' }); //执行sql语句并返回结果 db.query = function(sql){ return new Promise(function(resolve, reject){ if (!sql) { reject('传参错误!'); return; } pool.query(sql, function(err, rows, fields) { if (err) { console.log(err); reject(err) return; }; resolve(rows); }); }) }; //发送邮件,带附件 db.sendMail = function (xlsxname) { var transporter = nodemailer.createTransport({ service: 'qq', auth: { user: '452076103@qq.com', pass: 'drckgvaniifuxxxx' } }); var mailOptions = { from: '452076103@qq.com', to: `527828938@qq.com`, subject: '老板,您要的excel来了,格式您自己处理下!', html: `<h2>我发誓,我是手动导出的</h2>` , attachments:[{ filename : xlsxname, path : `./${xlsxname}` }] }; return new Promise(function(resolve, reject){ transporter.sendMail(mailOptions, function (error, info) { if (error) { reject(error); }else{ resolve(info); } }); }) } //格式化当前时间 db.nowDate = function(){ var date = new Date(); var fmtTwo = function (number) { return (number < 10 ? '0' : '') + number; } var yyyy = date.getFullYear(); var MM = fmtTwo(date.getMonth() + 1); var dd = fmtTwo(date.getDate()); var HH = fmtTwo(date.getHours()); var mm = fmtTwo(date.getMinutes()); var ss = fmtTwo(date.getSeconds()); return '' + yyyy + '-' + MM + '-' + dd + ' ' + HH + ':' + mm + ':' + ss; } module.exports = db;
var xlsx = require('node-xlsx'); var schedule = require("node-schedule"); var mysql = require('./promise'); var fs = require('fs'); var auto = function(){ mysql //查询数据,并转化成生成xlsx所需的格式 .query('select * from Users') .then(function(rows){ var datas = []; rows.forEach(function(row){ var newRow = []; for(var key in row){ newRow.push(row[key]); } datas.push(newRow); }) return Promise.resolve(datas); }) //生成xlsx文件 .then(function(datas){ var buffer = xlsx.build([{name: "今天的收入", data: datas}]); var xlsxname = `${mysql.nowDate().split(' ')[0]}.xlsx`; return new Promise(function(resolve, reject){ fs.writeFile(xlsxname, buffer, 'binary',function(err){ if (err) { throw new error('创建excel异常'); return; } resolve(xlsxname) }) }) }) //发送邮件,返回信息 .then(function(xlsxname){ return mysql.sendMail(xlsxname); }) .then(function(info){ console.log(info); }) //捕捉未处理的异常 .catch(function(e){ console.log(e); }); } var rule = new schedule.RecurrenceRule(); var t = []; for (var i = 0; i < 60; i++) { t.push(i); } var times = t; rule.second = times; schedule.scheduleJob(rule, function(){ auto(); });
nodejs实现,每天定时自动读取数据库数据-生成excel表格-发送给老板邮箱(promise版)
标签:
原文地址:http://blog.csdn.net/zzwwjjdj1/article/details/52273817