它读取csv文件,然后将其转换为json。问题是服务器在创建json文件之前启动,因此它不会发送任何内容。
我这里有一个csv文件:
25.07.2014 02:05:00.000,1.34650,1.34655,1.34650,1.34654,22.44,
25.07.2014 02:06:00.000,1.34654,1.34654,1.34651,1.34652,7.69,
25.07.2014 02:07:00.000,1.34652,1.34652,1.34646,1.34650,18.85,
25.07.2014 02:08:00.000,1.34652,1.34652,1.34650,1.34650,18.40,
25.07.2014 02:09:00.000,1.34652,1.34652,1.34650,1.34650,32.36,
25.07.2014 02:10:00.000,1.34650,1.34652,1.34650,1.34651,8.97,
(Pastebin)
这里有一个nodejs服务器代码:
var fs = require('fs');
var fileName = "test.csv";
var fileToArray = [];
var fileToJson;
fs.exists(fileName, function(exists) {
if (exists) {
fs.stat(fileName, function(error, stats) {
fs.open(fileName, "r", function(error, fd) {
var buffer = new Buffer(stats.size);
fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) {
var data = buffer.toString("utf8", 0, buffer.length);
var lines = data.split("\r\n");
var fileColCount = 6;
var lineInArray = [];
lines.forEach(function(line) {
lineInArray = line.split(',');
lineInArray.pop();
fileToArray.push(lineInArray);
})
console.log(fileToArray);
console.log('***********');
fileToJson = JSON.stringify(fileToArray);
console.log(fileToJson);
fs.close(fd);
});
});
});
}
});
var socketio = require('socket.io');
var io = socketio.listen(3636);
if (fileToJson) { // Empty?
console.log(fileToJson);
} else {
console.log('fileToJson empty !!!');
}
io.sockets.on('connection', function(socket) {
var clientIp = socket.request.connection.remoteAddress
console.log('Connection ip address: ' + clientIp);
socket.emit('candles', {
'jsoncandles': fileToJson
});
//send data to client
setInterval(function() {
socket.emit('date', {
'date': new Date()
});
}, 1000);
//recieve client data
socket.on('client_data', function(data) {
process.stdout.write(data.letter);
});
});
(Pastebin)
有什么想法吗?