我尝试在节点中运行pulsefft wasm库。
我加载了wasm模块,然后我使用这段代码来公开两个函数:
const loadPulse = require('./load-pulse')
const pulse = {}
module.exports = loadPulse().then((kissfft) => {
const lib = kissfft.exports
pulse['fftComplex'] = function (size) {
this.size = size;
this.fcfg = lib._kiss_fft_alloc(size, false);
this.icfg = lib._kiss_fft_alloc(size, true);
this.inptr = lib._malloc(size*8 + size*8);
this.outptr = this.inptr + size*8;
this.cin = new Float32Array(HEAPU8.buffer, this.inptr, size*2);
this.cout = new Float32Array(HEAPU8.buffer, this.outptr, size*2);
this.forward = function(cin) {
this.cin.set(cin);
lib._kiss_fft(this.fcfg, this.inptr, this.outptr);
return new Float32Array(HEAPU8.buffer,
this.outptr, this.size * 2);
}
this.inverse = function(cin) {
this.cin.set(cpx);
lib._kiss_fft(this.icfg, this.inptr, this.outptr);
return new Float32Array(HEAPU8.buffer,
this.outptr, this.size * 2);
}
this.dispose = function() {
lib._free(this.inptr);
lib._free(this.fcfg);
lib._free(this.icfg);
}
};
pulse['fftReal'] = function (size) {
this.size = size;
this.fcfg = lib._kiss_fftr_alloc(size, false);
this.icfg = lib._kiss_fftr_alloc(size, true);
this.rptr = lib._malloc(size*4 + (size+2)*4);
this.cptr = this.rptr + size*4;
this.ri = new Float32Array(HEAPU8.buffer, this.rptr, size);
this.ci = new Float32Array(HEAPU8.buffer, this.cptr, size+2);
this.forward = function(real) {
this.ri.set(real);
lib._kiss_fftr(this.fcfg, this.rptr, this.cptr);
return new Float32Array(HEAPU8.buffer, this.cptr, this.size + 2); //changed here
}
this.inverse = function(cpx) {
this.ci.set(cpx);
lib._kiss_fftri(this.icfg, this.cptr, this.rptr);
return new Float32Array(HEAPU8.buffer, this.rptr, this.size);
}
this.dispose = function() {
lib._free(this.rptr);
lib._free(this.fcfg);
lib._free(this.icfg);
}
}
return pulse
})
此代码最初来自pulsefft库,对节点进行了少量更改。当我运行代码时,我认为这个错误:
“ReferenceError:未定义HEAPU8”,我认为这个HEAPU8来自emscripten,位于从emscripten生成的js文件中。 我的浏览器工作正常。如何在节点中包含此模块?
我使用此代码加载模块:
const fs = require('fs');
const path = require('path')
module.exports = function () {
return new Promise((resolve, reject) => {
WebAssembly.compile(fs.readFileSync(path.resolve(__dirname, './src/WASMkissFFT.wasm'))).then((module) => {
const imports = {
env: {
DYNAMICTOP_PTR: 0,
STACKTOP: 0,
STACK_MAX: 0,
abort: function() {},
enlargeMemory: function() {},
getTotalMemory: function() {},
abortOnCannotGrowMemory: function() {},
___lock: function() {},
___syscall6: function() {},
___setErrNo: function() {},
___syscall140: function() {},
_emscripten_memcpy_big: function() {},
___syscall54: function() {},
___unlock: function() {},
___syscall146: function() {},
_exit: function() {},
memory: new WebAssembly.Memory({initial: 256, maximum: 256}),
table: new WebAssembly.Table({initial: 6, element: 'anyfunc', maximum: 6}),
memoryBase: 0,
tableBase: 0,
}
};
resolve(new WebAssembly.Instance(module, imports))
})
})
}