How to send data to tcp server on 1 minute interva

2019-09-16 17:29发布

I am reading a csv file line by line and storing in an array. Now I want to send line by line csv data to tcp server on 1 minute interval. My code is below ...what should I change in my code?

var net = require('net');
var csv = require("fast-csv");
var querystring = require('querystring');
var i;
var client = new net.Socket();
var csvData=[];
client.connect(7001, '54.168.67.139', function() {
    console.log('Connected');
    csv
    .fromPath("wabco.csv")
    .on("data", function(data){
    var res = "";
    for (i = 2; i < data.length; i++) {
            if (i == data.length-1) res += data[i];
            else res += data[i]+",";
    }
    res = res.substring(1,res.length-1);
    //client.write(res);
    //console.log(res);
    csvData.push(res);
})
.on("end", function(){
    //client.write(csvData[5]);
    for (i = 0; i < csvData.length; i++) {
            client.write(csvData[i]);
    }
});
});

client.on('close', function() {
    console.log('Connection closed');
});

标签: node.js tcp
1条回答
对你真心纯属浪费
2楼-- · 2019-09-16 18:13

Assuming csvData is an array with the lines of that you want to send, you can do something like :

.on("end", function(){

    let interval = 0,
        i = 0;

    interval = setInterval( function() {

        // Send it
        client.write( csvData[ i++ ] );

        // Stop when we are on the last item
        if ( csvData.length === i ) { clearInterval( interval ); }

    }, 1000 * 60 )

});
查看更多
登录 后发表回答