首页 > 编程语言 >node基础

node基础

时间:2023-06-26 19:12:17浏览次数:47  
标签:node function console log err 基础 var

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;

  

 

标签:node,function,console,log,err,基础,var
From: https://www.cnblogs.com/kunyashaw/p/17506523.html

相关文章

  • angualr基础
    一、Angular概述基于命令行的开发方式? ①hotreload ②编译工作 ③集成了webpack打包工具 。。。。angular.cn中文angular.io正式官网angular.cn/guide/styleguide风格指南1、what? angular是一个Google推出的js框架,是以模块为基本单位,模块又可以包含组件、指令、过滤器。。......
  • 聊一聊 Lua 的基础数据类型:数值、布尔、字符串
    楔子任何一门语言都提供了不同类型的数据结构,那么Lua中都有哪些数据结构呢?nil:空boolean:布尔类型,分别是true和falsenumber:数值类型,整型和浮点型都属于numberstring:字符串table:表function:函数userdata:用户数据thread:线程Lua总共提供了以上8种数据类型,目前只需要......
  • Linux基础26 rsync服务, 三种传输方式
    Rsync服务一、备份1.什么是备份?备份就是把重要的数据或文件再次复制一份保存起来(给源文件增加一个副本)2.为什么要备份?数据很重要!!!出现故障之后,需要恢复数据(软件服务出现问题几率很小,80%都是人为故障)3.能不能不做备份对于不重要的数据,可以不做备份对于不必要的数据可......
  • Python基础知识
    1.变量和简单数据类型1.1变量变量只能包含字母、数字、下划线,并且不能以数字开头变量名不能包含空格不要讲python关键字和函数作为变量名。变量名应简短又具有描述行被赋值的内容应该用双引号或单引号括起来1.2字符串title():将字符串首字母变为大写upper():将字符串......
  • Linux基础25 架构, 安装模板机
    架构一、名词的介绍1.项目:手机的APP,买一个APP就是一个项目,针对互联网行业,一家电商公司就是一个项目2.架构:维护一个项目所有组件组成一个整体lnmp:linuxnginxmysqlphplamp:linuxApachemysqlphplnmt:linuxnginxmysqltomcatlamt:linuxApacheMysqlTomcat#除了这些......
  • 机械设计基础
    1.1绪论:机械的组成概述1.2课程的内容、性质和任务1.3即系设计的基本要求及一般程序思考题第二章:平面机构的结构分析2.1平面结构的机构分析2.2机构的组成和平面机构运动简图绘制2.3平面机构自由度的计算2.4平面机构的组成原理、结构分类和结构分析思考题习题第三章:平面连杆机构3.1平......
  • Selenium基础:特殊Dom结构操作 07
    特殊Dom结构是指对元素不能直接操作,需要进行特殊定位切换到它所在的Dom结构,然后才能对其元素进行操作1、windows弹窗--alertconfirmprompt使用driver.switch_to.alert方法alert类操作方法:accept():确定dismiss():取消text():获取弹出框内的内容send_keys(keysToSend):输入......
  • JavaScript基础第06天笔记
    1-内置对象1.1内置对象JavaScript中的对象分为3种:自定义对象、内置对象、浏览器对象​前面两种对象是JS基础内容,属于ECMAScript;第三个浏览器对象属于JS独有的,JSAPI讲解内置对象就是指JS语言自带的一些对象,这些对象供开发者使用,并提供了一些常用的或是最基......
  • MAC安装多个版本node命令
    背景:在实际项目开发中,不同的项目我们往往需要用到不同版本的node做支持,并且需要根据项目需要切换,以下就是常用的命令行。Mac下使用n去安装多个指定版本的Node.js,并使用命令随时切换。1.全局安装nnpminstall-gn2.指定版本的Node安装sudo-En16.17.03.查看已经安装的Noden......
  • 核心交换机六个基础知识
    一、背板带宽背板带宽也称交换容量,是交换机接口处理器或接口卡和数据总线间所能吞吐的最大数据量,就像是立交桥所拥有的车道的总和。由于所有端口间的通信都需要通过背板完成,所以背板所能提供的带宽,就成为端口间并发通信时的瓶颈。带宽越大,提供给各端口的可用带宽越大,数据交换速......