我有这样的方法:
// Parse a whole file
fs.readFile("klv-file.klv", (err, file) => {
var KLVdata = KLV.parseKLVfile(file, options);
var packets = KLVdata.packets;
var nDropped = KLVdata.nDropped;
});在一个小Node应用程序中。
如何在此对象之外获取可变数据包?
发布于 2022-07-14 17:40:22
其实很简单。定义函数外部的变量,并在其中设置它们。如下所示:
// Define variables
var packets = null;
var nDropped = null;
// Parse a whole file
fs.readFile("klv-file.klv", (err, file) => {
var KLVdata = KLV.parseKLVfile(file, options);
packets = KLVdata.packets;
nDropped = KLVdata.nDropped;
});
function doSomething(){
// you can now use the variables anywhere
}另外:确保只使用已定义的变量。
// Define variables
var packets = null;
var nDropped = null;
// Parse a whole file
fs.readFile("klv-file.klv", (err, file) => {
var KLVdata = KLV.parseKLVfile(file, options);
packets = KLVdata.packets;
nDropped = KLVdata.nDropped;
packetsReady(); // your callback function
});
function packetsReady(){
// should only be called once the packets are ready
processPackets(packets);
}发布于 2022-07-14 17:40:33
简单地把它传递给一个函数
let packets;
let nDropped;
function processKLV(KLVdata){
packets = KLVdata.packets;
nDropped = KLVdata.nDropped;
}
// Parse a whole file
fs.readFile("klv-file.klv", (err, file) => {
processKLV(KLV.parseKLVfile(file, options));
});https://stackoverflow.com/questions/72984569
复制相似问题