node-example.js 5.0 KB
Newer Older
S
StoneT2000 已提交
1 2
/* This example is to show the preferred way to use the td-connector */
/* To run, enter node path/to/node-example.js */
3
// Get the td-connector package
L
liu0x54 已提交
4
const taos = require('td2.0-connector');
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

/* We will connect to TDengine by passing an object comprised of connection options to taos.connect and store the
 * connection to the variable conn
 */
/*
 * Connection Options
 * host: the host to connect to
 * user: the use to login as
 * password: the password for the above user to login
 * config: the location of the taos.cfg file, by default it is in /etc/taos
 * port: the port we connect through
 */
var conn = taos.connect({host:"127.0.0.1", user:"root", password:"taosdata", config:"/etc/taos",port:0});

// Initialize our TDengineCursor, which we use to interact with TDengine
var c1 = conn.cursor();

S
StoneT2000 已提交
22
// c1.query(query) will return a TaosQuery object, of which then we can execute. The execute function then returns a promise
23 24
// Let's create a database named db
try {
25 26 27
	c1.execute('create database if not exists db;');
  //var query = c1.query('create database if not exists db;');
  //query.execute();
28 29 30 31 32 33
}
catch(err) {
  conn.close();
  throw err;
}

S
StoneT2000 已提交
34 35
// Now we will use database db. As this query won't return any results,
// we can simplify the code and directly use the c1.execute() function. No need for a TaosQuery object to wrap around the query
36 37 38 39 40 41 42 43 44 45
try {
  c1.execute('use db;');
}
catch (err) {
  conn.close();
  throw err;
}

// Let's create a table called weather
// which stores some weather data like humidity, AQI (air quality index), temperature, and some notes as text
S
StoneT2000 已提交
46 47
// We can also immedietely execute a TaosQuery object by passing true as the secodn argument
// This will then return a promise that we can then attach a callback function to
48
try {
S
StoneT2000 已提交
49 50 51 52 53 54
  var promise = c1.query('create table if not exists weather (ts timestamp, humidity smallint, aqi int, temperature float, notes binary(30));', true);
  promise.then(function(){
    console.log("Table created!");
  }).catch(function() {
    console.log("Table couldn't be created.")
  });
55 56 57 58 59 60 61
}
catch (err) {
  conn.close();
  throw err;
}

// Let's get the description of the table weather
S
StoneT2000 已提交
62 63
// When using a TaosQuery object and then executing it, upon success it returns a TaosResult object, which is a wrapper around the
// retrieved data and allows us to easily access data and manipulate or display it.
64
try {
S
StoneT2000 已提交
65 66 67 68
  c1.query('describe db.weather;').execute().then(function(result){
    // Result is an instance of TaosResult and has the function pretty() which instantly logs a prettified version to the console
    result.pretty();
  });
69 70 71 72 73 74
}
catch (err) {
  conn.close();
  throw err;
}

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

Date.prototype.Format = function(fmt){
    var o = {
    	'M+': this.getMonth() + 1,
    	'd+': this.getDate(),
    	'H+': this.getHours(),
    	'm+': this.getMinutes(),
        's+': this.getSeconds(),
    	'S+': this.getMilliseconds()
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
		if (new RegExp('(' + k + ')').test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(String(o[k]).length)));
        }
    }
    return fmt;
}


97
// Let's try to insert some random generated data to test with
S
StoneT2000 已提交
98 99
// We will use the bind function of the TaosQuery object to easily bind values to question marks in the query
// For Timestamps, a normal Datetime object or TaosTimestamp or milliseconds can be passed in through the bind function
100 101 102
let stime = new Date();
let interval = 1000;
try {
S
StoneT2000 已提交
103
  for (let i = 0; i < 1000; i++) {
104
    stime.setMilliseconds(stime.getMilliseconds() + interval);
105 106 107
    
    //console.log(stime.Format('yyyy-MM-dd HH:mm:ss.SSS'));    

S
StoneT2000 已提交
108
    let insertData = [stime,
109 110 111
                      parseInt(Math.random()*100),
                      parseInt(Math.random()*300),
                      parseFloat(Math.random()*10 + 30),
112
                      "Note"];
S
StoneT2000 已提交
113
    //c1.execute('insert into db.weather values(' + insertData.join(',') + ' );');
114 115 116 117
    
    //var query = c1.query('insert into db.weather values(?, ?, ?, ?, ?);').bind(insertData);
    //query.execute();
    c1.execute('insert into db.weather values(\"'+stime.Format('yyyy-MM-dd HH:mm:ss.SSS')+'\",'+parseInt(Math.random() * 100)+','+parseInt(Math.random() * 300)+','+parseFloat(Math.random()*10 + 30)+',"Note");');
118
  }
119
}catch (err) {
120 121 122 123 124 125 126
  conn.close();
  throw err;
}

// Now let's look at our newly inserted data
var retrievedData;
try {
S
StoneT2000 已提交
127
  c1.query('select * from db.weather limit 5 offset 100;', true).then(function(result){
128 129
    //result.pretty();
	console.log('=========>'+JSON.stringify(result));
S
StoneT2000 已提交
130 131
    // Neat!
  });
132 133 134 135 136 137 138 139 140

}
catch (err) {
  conn.close();
  throw err;
}

// Let's try running some basic functions
try {
S
StoneT2000 已提交
141 142 143 144
  c1.query('select count(*), avg(temperature), max(temperature), min(temperature), stddev(temperature) from db.weather;', true)
  .then(function(result) {
    result.pretty();
  })
145 146 147 148 149 150 151 152 153
}
catch(err) {
  conn.close();
  throw err;
}

conn.close();

// Feel free to fork this repository or copy this code and start developing your own apps and backends with NodeJS and TDengine!