kunyashaw博客主页 关注kunyashaw新博客 关于kunyashaw 转到底部

node基础

1、node本地化日志

//本地化日志及按日期切割
const winston = require('winston');
require('winston-daily-rotate-file');

var transport = new winston.transports.DailyRotateFile({
  filename: 'logs/console-%DATE%.log',
  datePattern: 'YYYY-MM-DD-HH',
  zippedArchive: true,
  maxSize: '20m',
  maxFiles: '14d'
});


const logConfiguration = {
    transports: [
        transport
        // new winston.transports.File({
        //     filename: 'logs/console.log'
        // })
    ],
    format: winston.format.combine(
        winston.format.label({
            label: `HealthTimerTask `
        }),
        winston.format.timestamp({
           format: 'MMM-DD-YYYY HH:mm:ss'
       }),
        winston.format.printf(info => `${info.level}: ${info.label}: ${[info.timestamp]}: ${info.message}`),
    )
};
const logger = winston.createLogger(logConfiguration);

module.exports = logger

  

2、node表格处理

npm install excel-report

var nodeExcel = require('excel-export');


//处理excel
var conf = {}
conf.stylesXmlFile = "styles.xml";
conf.cols = [{
    caption: '姓名',
    type: 'string',
    beforeCellWrite: function (row, cellData) {
        console.log(row)
        console.log(cellData)
        return cellData;
    },
    width: 18.7109375
},
             {
                 caption: '身份证',
                 type: 'string',
                 beforeCellWrite: function (row, cellData) {
                     return cellData;
                 },
                 width: 28.7109375
             },
             {
                 caption: '电话',
                 type: 'string',
                 beforeCellWrite: function (row, cellData) {
                     return cellData;
                 },
                 width: 18.7109375
             },
             {
                 caption: '持卡人信息',
                 type: 'string',
                 beforeCellWrite: function (row, cellData) {
                     return cellData;
                 },
                 width: 18.7109375
             },
             {
                 caption: '开户卡地址',
                 type: 'string',
                 beforeCellWrite: function (row, cellData) {
                     return cellData;
                 },
                 width: 28.7109375
             },
             {
                 caption: '银行卡号',
                 type: 'string',
                 beforeCellWrite: function (row, cellData) {
                     return cellData;
                 },
                 width: 28.7109375
             },
             {
                 caption: '提交退款日期',
                 type: 'string',
                 beforeCellWrite: function (row, cellData) {
                     return cellData;
                 },
                 width: 18.7109375
             }
            ];
conf.rows = [];

for(var i=0;i<result2.length;i++){
    var obj = [
        result2[i].name,
        result2[i].id_number,
        result2[i].mobile_phone,
        result2[i].bank_card_holder,
        result2[i].bank_detail_address,
        result2[i].other_contact,
        result2[i].refund_date
    ]
    conf.rows.push(obj)
}

var result = nodeExcel.execute(conf);
res.setHeader('Content-Type', 'application/vnd.openxmlformats');
res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
res.end(result, 'binary');

  

3、node 作为微服务注册到consul,获取和设置值

const Consul = require('consul');
var serviceName = 'node-parse-url'

const consul = new Consul({
    host: '1**.2*.4.47',
    port: 8500,
    promisify: true,
});

consul.agent.service.register({
    name: serviceName,
    address: '1**.**.5.10',
    port: 3000,
    check: {
        http: 'http://1**.1*.5.10:3000/health',
        interval: '10s',
        timeout: '5s',
    }
}, function (err, result) {
    if (err) {
        console.error(err);
        throw err;
    }

    console.log(serviceName + ' 注册成功!');
})




    consul.kv.get('zgt').then((result) => {
        if (result && result.Value) {
            if (result.Value == 'on') {
                res.send({ status: 200, data: true })
            } else {
                res.send({ status: 200, data: false })
            }
        } else {
            res.send({ status: 200, data: false })
        }
    })

  

 

4、node 限流

const slowDown = require("express-slow-down");


// 1个ip,1s内最多相应5个请求,超出5个就排队等待吧
const speedLimiter = slowDown({
    windowMs: 1000,//1s
    delayAfter: 2, // 最多2个请求
    delayMs: 2000 // 超2后延后2s后排队

});
app.use(speedLimiter);

  

5、node 在线文档

1、全局安装
npm i -g apidoc

2、在node项目根目录下创建apidoc.json文件
{
  "name": "node-server", 
  "version": "1.0.0", 
  "description": "node-server项目API文档", 
  "title": "node-server API", 
  "url1" : "http://1**.1*.5.6:8081/", 
  "url" : "http://localhost:8081/", 
  "sampleUrl": "http://localhost:8081/",
  "forceLanguage":"zh-cn",
  "template": {
    "withCompare": true,
    "withGenerator": true
  }

}

3、配置    
指定静态资源文件夹
server.use('/apidoc',express.static('public'));

4、在接口处添加规则
/**
 * 查询公司信息是否存在 
 * @api {POST} user/checkCompanyExists 查询公司信息是否存在 
 * @apiDescription 查询公司信息是否存在 
 * @apiName checkCompanyExists
 * @apiBody (body参数) {String} company_name
 * @apiBody (body参数) {String} mobile_phone
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/checkCompanyExists', (req, res) => {}))

  

6、操作redis

const redis = require('redis');
// todo
const config = {
    url:'1**.1*.5.6',
    port:6379,
    password:''
}

const client = redis.createClient(config.port, config.url); // 实例redis对象

//连接错误处理
client.on("error", err => {
    console.log('redis connect err', err);
});

client.on('connect', () => {
    console.log('redis connect success');
})

//验证redis
client.auth(config.password);

const redisHelper = {};

/**
 * redisHelper setString function
 * @param key
 * @param value
 * @param expire
 */
redisHelper.setString = (key, value, expire) => {
    return new Promise((resolve, reject) => {
        client.set(key, value, function (err, result) {

            if (err) {
                console.log(err);
                reject(err);
            }

            if (!isNaN(expire) && expire > 0) {
                client.expire(key, parseInt(expire));
            }
            resolve(result)
        })
    })
}

/**
 * redisHelper getString function
 * @param key
 */
redisHelper.getString = (key) => {
    return new Promise((resolve, reject) => {
        client.get(key, function (err, result) {
            if (err) {
                console.log(err);
                reject(err)
            }
            resolve(result)
        });
    })
}

module.exports = redisHelper;

  

 

7、node处理express请求参数

get请求携带参数:

        方式1: http://localhost:3000/detail?id=1

          req.query.id

        方式2: http://localhost:3000/oc/10

          app.get('/oc/:myid',()=>{})

          req.params.myid

      post请求携带参数:

        方式1:

          var querystring = require('querystring');

          app.post('/login',(req,res)=>{

            req.on('data',(buf)=>{

              var obj = querystring.parse(buf.toString());

              obj.***

            })

          })

  

 

8、node发短信

var uuid = require('node-uuid');
var crypto = require('crypto');
var moment = require('moment');
var http = require('http');
var alidayuUrl = 'http://dysmsapi.aliyuncs.com/';
// var OPAPI = require('opapi');
var config = {
    AppKey: '',
    AppSecret: ''
};
var obj = {
    AccessKeyId: config.AppKey,
    Action: 'SendSms',
    Format: 'JSON',
    PhoneNumbers: '',
    RegionId: 'cn-hangzhou',
    SignName: '',
    SignatureMethod: 'HMAC-SHA1',
    SignatureNonce: uuid.v1(),
    SignatureVersion: '1.0',
    TemplateCode: 'SMS_1769409**',
    TemplateParam: '{"code":"123456"}',
    Timestamp: '',
    Version: '2017-05-25'
}
var sms = {
    NORMAL_TEMPPLATE: 'SMS_787700**',
    REGISTER_TEMPLATE: 'SMS_759952**',
    CHANGEPROJECT_TEMPLATE: 'SMS_759952**',
    FORGETPASSS_TEMPLATE: 'SMS_759952**',
    sendMessage: function (phone, TemplateCode, TemplateParam, callback) {
        var sendurl = this.url(phone, TemplateCode, TemplateParam);
        var req = http.request(sendurl, function (res) {
            var status = res.statusCode;
            if (status != 200) {
                callback(new Error('网络异常'));
            }
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                var value = JSON.parse(chunk);
                if (value.Code != 'OK') {
                    console.log(chunk);
                    callback(new Error('短信发送异常'));
                } else {
                    callback(null);
                }
            }).on('error', function (e) {
                callback(new Error('发送短信异常'));
            });
        });
        req.write('执行完毕');
        req.end();
    },
    sign: function (params, accessSecret) {
        var param = {}, qstring = [];
        var oa = Object.keys(params);
        for (var i = 0; i < oa.length; i++) {
            param[oa[i]] = params[oa[i]];
        }
        for (var key in param) {
            qstring.push(encodeURIComponent(key) + '=' + encodeURIComponent(param[key]));
        }
        qstring = qstring.join('&');
        var StringToSign = 'GET' + '&' + encodeURIComponent('/') + '&' + encodeURIComponent(qstring);
        accessSecret = accessSecret + '&';
        var signature = crypto.createHmac('sha1', accessSecret).update(StringToSign).digest().toString('base64');
        signature = signature.replace(/\*/, '%2A').replace(/%7E/, '~');
        return signature;
    },
    url: function (phone, TemplateCode, TemplateParam) {
        var timestamp = moment(new Date().getTime() - 3600 * 1000 * 8).format("YYYY-MM-DDTHH:mm:ss") + 'Z';
        obj.PhoneNumbers = phone;
        obj.SignatureNonce = uuid.v1();
        obj.TemplateCode = TemplateCode;
        obj.TemplateParam = TemplateParam;
        obj.Timestamp = timestamp;
        var sign = this.sign(obj, config.AppSecret);
        var arr = [];
        for (var p in obj) {
            arr.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
        }
        arr.push(encodeURIComponent('Signature') + '=' + encodeURIComponent(sign))
        var msg = arr.join('&')
        var sendurl = alidayuUrl + '?' + msg;
        return sendurl;
    }
}
module.exports = sms;

  

9、node操作es

//express结合es操作

var elasticsearch = require('elasticsearch');
var elasticClient = new elasticsearch.Client({
  host: '1**.1*.5.48:9200'
});

app.listen(4200,()=>{
    console.log("server starts in port 4200")
})


app.get("/estest",(req,res)=>{

    elasticClient.search({
        index: req.query.index
    
    }) .then(function (response) {
     var hits = response.hits.hits;
     console.log(response);
     res.send(response)
      });

})



var elasticsearch = require('elasticsearch');
var elasticClient = new elasticsearch.Client({
    host: '1**.**.5.4*:9200'
});
var searchInfo = {
    index: "news_tong",
    body: {
        query: {
            match_phrase: {
                id: "20211213-00022"
            }
        },
        _source: ["author", "typeName", "title", "publishTime", "intro", 'isTop'],
    }
}
var updateInfo = {
    index: "news_tong",
    body: {
        query: {
            match_phrase: {
                id: "20211213-00022"
            }
        },
        script: {
            "source": "ctx._source['isTop'] = params['one']",
            "params": {
                "one": true,
            }
        }
    }
}
var test = async function (searchInfo) {
    var response = await elasticClient.search(searchInfo)
    if (response.hits.total > 0) {
        console.log('数据存在 isTop is ', response.hits.hits[0]._source.isTop);
        //更新
        if (response.hits.hits[0]._source.isTop == false) {
            var response2 = await elasticClient.updateByQuery(updateInfo)
            if (response2.updated >= 1) {
                console.log('更新成功')
            } else {
                console.log('更新失败')
            }
            process.exit(0)
        } else {
            console.log('无须更新')
            process.exit(0)
        }


    } else {
        console.log('数据不存在')
        process.exit(0)
    }



}

test(searchInfo)

  

10、node发邮件

var email   = require("emailjs");
console.log(email)
var client  = new email.SMTPClient({
    user:    "",      // 你的QQ用户
    password:"",           // 注意,不是QQ密码,而是刚才生成的授权码
    host:    "smtp.mxhichina.com",         // 主机,不改
    ssl:     true                   // 使用ssl
});

var mail = {}
//开始发送邮件
mail.sendMail = (text,to,subject,callback)=>{
    client.send({
        text:    text,       //邮件内容
        from:    "",        //谁发送的
        to:      to,       //发送给谁的
        subject: subject          //邮件主题
    }, callback );
}



module.exports = mail;

  

 

posted @ 2023-06-26 19:02  kunyashaw  阅读(35)  评论(0编辑  收藏  举报
回到顶部