Node.JS 读写数据到 influxDB, 目前已经有一个库 https://github.com/node-influx/node-influx , 这个库功能非常强大, 但是我个人使用这个库的时候, 遇到无法解决的问题.
使用 curl 都可以写数据到 influxDB, 但是用 node-influx 总是报错, 搞了半天也无法解决, 就索性不用它了.
influxDB 提供 HTTP 的 API, 也就是说 Node.JS 中的 https://github.com/axios/axios 或者 https://github.com/request/request 等 HTTP 客户端工具是可以直接和 influx 交互的.
需要注意的一点是, 写到 influxDB 的数据格式必须是二进制流.
为此, 要做两件事情:
1. 字符串转二进制
const data = Buffer.from('mymeas,mytag=1 myfield=90')
2. 设置请求 Content-Type 为二进制
'Content-Type': 'application/octet-stream'
完整代码
- const axios = require('axios')
- const data = Buffer.from('mylog,name=wdd error_count=2003,no_send=0')
- axios({
- url: 'http://localhost:8923/write?db=poc&rp=poc',
- method: 'post',
- headers: {
- 'Content-Type': 'application/octet-stream'
- },
- data: data
- })
- .then((res) => {
- console.log('ok')
- // console.log(res)
- })
- .catch((err) => {
- console.log('err')
- })
使用 axios 或者 requst 这种底层库的好处是, 你用 curl 做的成功的任何操作, 都可以转换成 axios 或 request 的请求, 而不依赖与其他库.
来源: https://www.jb51.net/article/149603.htm