【发布时间】:2016-04-23 05:25:01
【问题描述】:
尝试(半成功)从 TCP 套接字中提取权重。然后我想将数据输出到 JSON 字符串,这样我就可以将它包装成一些角度。您可以在控制台中看到我正在接收权重,我最终会删除文本项的开头和结尾,因此输出看起来像:
{ "scaleA": '43636LG',"scaleB" 等......}
weightclient.js
'use strict'
var net = require('net');
var HOST = '192.168.1.17';
var PORT = 1337;
var client = new net.Socket();
var weight = function(){
var weights = {};
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.on('data', function(data) {
// console.log('DATA: ' + data);
weights.scaleA = data.toString();
console.log(weights);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
});
return {
weights
};
}();
console.log(weight);
module.exports = weight;
index.js
var express = require('express');
var router = express.Router();
var net = require('net');
var getweight = require('../weightclient.js');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/weight', function(req, res) {
getweight.weight(function(err, data){
console.log(data);
});
});
module.exports = router;
控制台(输出):
node bin/www
{ weights: {} }
CONNECTED TO: 192.168.1.17:1337
{ scaleA: '\u0002 43636LG \r\n' }
Connection closed
GET /weight 500 2973.083 ms - 1131
GET /stylesheets/style.css 304 25.835 ms - -
网页输出:
getweight.weight is not a function
TypeError: getweight.weight is not a function
at /home/pi/socketio-test/routes/index.js:13:15
at Layer.handle [as handle_request] (/home/pi/socketio-test/node_modules/express/lib/router/layer.js:95:5)
at next (/home/pi/socketio-test/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/home/pi/socketio-test/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/pi/socketio-test/node_modules/express/lib/router/layer.js:95:5)
at /home/pi/socketio-test/node_modules/express/lib/router/index.js:277:22
at Function.process_params (/home/pi/socketio-test/node_modules/express/lib/router/index.js:330:12)
at next (/home/pi/socketio-test/node_modules/express/lib/router/index.js:271:10)
at Function.handle (/home/pi/socketio-test/node_modules/express/lib/router/index.js:176:3)
at router (/home/pi/socketio-test/node_modules/express/lib/router/index.js:46:12)
想法建议..还在学习node和js,不胜感激任何指针或参考婚姻。
【问题讨论】:
-
除非我遗漏了一些关键,否则您的
return { weights };是无效的 javascript。
标签: javascript angularjs json node.js sockets