I am using Socket in Node.js to get data and save them in buffer using utf8 format. And those data are number, I want to do some calculation but result in NaN.
var client = new net.Socket();
client.connect(PORT, HOST, function() {
var commandstr = new Buffer("A5021E", "hex")
client.write(commandstr);
});
client.on('data', function(data) {
var buff = new Buffer(data, 'utf8');
ProcessBuffer(buff);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
ProcessBuffer = function(recv_msg){
var bp_s = recv_msg.toString('utf8').substring(65, 69);
console.log(parseInt(bp_s + 5)); //Do the calculation here and return in NaN
}
You need to convert the bp_s variable, which is a string, to a number before adding it to 5.
You can use the parseInt function [1]: parseInt(bp_s)
.
So, your last line would be:
console.log(parseInt(bp_s) + 5);
Note that the parseInt function also allows you to define the radix of your number, as the second argument to the function. By default it is 10.
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.