[英]Buffer issue in Node.js
I have one small issue while using buffers in Node.js 在Node.js中使用缓冲区时遇到一个小问题
I have defined my constant buffer like this. 我已经定义了这样的常量缓冲区。
var commands = {
BufferOne : new Buffer([0XCA, 0X11, 0X00, 0X00, 0X60, 0X01,
0X00, 0X01, 0X08, 0X07, 0X6D, 0X00, 0X00, 0X00,
0X00, 0X00, 0X4F, 0X41, 0X30, 0X30, 0X00])
}
Now later when I receive any specific event in program i want to update 14, 15 from that. 现在稍后,当我在程序中收到任何特定事件时,我想从中更新14、15。
Let's say for example in one of the function i will create local variable 假设在其中一个函数中,我将创建局部变量
var bufferCopy = commands.BufferOne;
bufferCopy[14] = "0X02";
bufferCopy[15] = "0X00";
Then I want to use that bufferCopy to send to the serial port but my functionality doesn't work. 然后,我想使用该bufferCopy发送到串行端口,但是我的功能不起作用。
Now same way from above if I do like this 现在,如果我喜欢这样,也可以从上面
var bufferCopy = new Buffer([0XCA, 0X11, 0X00, 0X00, 0X60, 0X01, 0X00,
0X01, 0X08, 0X07, 0X6D, 0X00, 0X00, 0X00, 0X00, 0X00, 0X4F, 0X41,
0X30, 0X30, 0X00]);
bufferCopy[14] = "0X02";
bufferCopy[15] = "0X00";
Then it works fine. 然后工作正常。 I can get the result on the serialport. 我可以在串行端口上得到结果。
So I am not able to understand why i can't create any local variable from constant declared above. 所以我不明白为什么我不能从上面声明的常量创建任何局部变量。
The reason i want to use constant is because i want to move those all constant to some server so I can send those commands from server instead of keeping in Node Program itself. 我想使用常量的原因是因为我想将所有常量都移动到某个服务器,以便可以从服务器发送那些命令,而不必保留在Node Program本身中。
When you assign a Buffer like that ( var bufferCopy = commands.BufferOne;
), it's creating a reference (just like all object assignments in JavaScript) to the original Buffer, so you are actually modifying commands.BufferOne
instead of a copy of commands.BufferOne
. 当您这样分配一个Buffer( var bufferCopy = commands.BufferOne;
)时,它正在创建对原始Buffer的引用(就像JavaScript中的所有对象分配一样),因此您实际上是在修改commands.BufferOne
而不是commands.BufferOne
的副本commands.BufferOne
。
If you want a copy, you will have to explicitly create a copy, like: 如果要复制,则必须显式创建一个副本,例如:
var bufferCopy = new Buffer(commands.BufferOne);
bufferCopy[14] = "0X02";
bufferCopy[15] = "0X00";
Then only bufferCopy
will be modified and not also commands.BufferOne
. 那么只有bufferCopy
将被修改,而不是也commands.BufferOne
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.