| 57 | } |
| 58 | |
| 59 | const stringify = function () { |
| 60 | let data, options, callback; |
| 61 | for (const i in arguments) { |
| 62 | const argument = arguments[i]; |
| 63 | const type = typeof argument; |
| 64 | if (data === undefined && Array.isArray(argument)) { |
| 65 | data = argument; |
| 66 | } else if (options === undefined && is_object(argument)) { |
| 67 | options = argument; |
| 68 | } else if (callback === undefined && type === "function") { |
| 69 | callback = argument; |
| 70 | } else { |
| 71 | throw new CsvError("CSV_INVALID_ARGUMENT", [ |
| 72 | "Invalid argument:", |
| 73 | `got ${JSON.stringify(argument)} at index ${i}`, |
| 74 | ]); |
| 75 | } |
| 76 | } |
| 77 | const stringifier = new Stringifier(options); |
| 78 | if (callback) { |
| 79 | const chunks = []; |
| 80 | stringifier.on("readable", function () { |
| 81 | let chunk; |
| 82 | while ((chunk = this.read()) !== null) { |
| 83 | chunks.push(chunk); |
| 84 | } |
| 85 | }); |
| 86 | stringifier.on("error", function (err) { |
| 87 | callback(err); |
| 88 | }); |
| 89 | stringifier.on("end", function () { |
| 90 | try { |
| 91 | callback(undefined, chunks.join("")); |
| 92 | } catch (err) { |
| 93 | // This can happen if the `chunks` is extremely long; it may throw |
| 94 | // "Cannot create a string longer than 0x1fffffe8 characters" |
| 95 | // See [#386](https://github.com/adaltas/node-csv/pull/386) |
| 96 | callback(err); |
| 97 | return; |
| 98 | } |
| 99 | }); |
| 100 | } |
| 101 | if (data !== undefined) { |
| 102 | const writer = function () { |
| 103 | for (const record of data) { |
| 104 | stringifier.write(record); |
| 105 | } |
| 106 | stringifier.end(); |
| 107 | }; |
| 108 | // Support Deno, Rollup doesn't provide a shim for setImmediate |
| 109 | if (typeof setImmediate === "function") { |
| 110 | setImmediate(writer); |
| 111 | } else { |
| 112 | setTimeout(writer, 0); |
| 113 | } |
| 114 | } |
| 115 | return stringifier; |
| 116 | }; |