Debian Codegraph @

wasm/nodejs/src/filesystem.js

raw
1 const decoder = new TextDecoder("utf-8");
2
3 function clearArray(array) {
4 while (array.length > 0) {
5 array.pop();
6 }
7 }
8
9 export const csoundWasiJsMessageCallback = ({ memory, streamBuffer, messagePort }) => (
10 csound,
11 attribute,
12 length_,
13 offset,
14 ) => {
15 const buf = new Uint8Array(memory.buffer, offset, length_);
16 const string = decoder.decode(buf);
17 const endsWithNewline = /\n$/g.test(string);
18 const startsWithNewline = /^\n/g.test(string);
19 const chunks = string.split("\n").filter((item) => item.length > 0);
20 const printableChunks = [];
21
22 if ((chunks.length === 0 && endsWithNewline) || startsWithNewline) {
23 printableChunks.push(streamBuffer.join(""));
24 clearArray(streamBuffer);
25 }
26 chunks.forEach((chunk, index) => {
27 // if it's last chunk
28 if (index + 1 === chunks.length) {
29 if (endsWithNewline) {
30 if (index === 0) {
31 printableChunks.push(streamBuffer.join("") + chunk);
32 clearArray(streamBuffer);
33 } else {
34 printableChunks.push(chunk);
35 }
36 } else {
37 streamBuffer.push(chunk);
38 }
39 } else if (index === 0) {
40 printableChunks.push(streamBuffer.join("") + chunk);
41 clearArray(streamBuffer);
42 } else {
43 printableChunks.push(chunk);
44 }
45 });
46
47 printableChunks.forEach((chunk) => {
48 console.log(chunk.replace(/(\r\n|\n|\r)/gm, ""));
49 // if (messagePort.ready) {
50 // messagePort.post(chunk.replace(/(\r\n|\n|\r)/gm, ""));
51 // }
52 });
53 };