myteril / node-win-printer

A Node.js package to print PDF files and get the information of available printers on Windows.
Apache License 2.0
3 stars 0 forks source link

a bug from Array #1

Closed CloudWoR closed 7 months ago

CloudWoR commented 7 months ago

While studying your program of converting characters to objects, I discovered an error: when trying to convert a string to an array using JSON.parse(), an error occurred. Here is my conversion program. Please correct it for me.


  /**获取打印机列表 */
  public async getPrinters(): Promise<Printer[]> {
    const codepage = await this.getTerminalCodePage();
    const command = 'wmic printer list /format:list';
    return new Promise<Printer[]>((resolve) => {
      exec(command, { encoding: 'buffer' }, (error, stdout, stderr) => {
        if (error && stderr.length > 0) {
          resolve([]);
        }
        const stdoutStr = iconv.decode(stdout, codepage);
        if (!stdoutStr || stdoutStr.length < 1) resolve([]);
        const printers = stdoutStr.replace(/\r/ig, '').split('\n\n\n').map((item) => {
          if (item.length <= 1) return;
          const map = new Map<string, number | string | boolean | string[]>();
          item.split('\n').map((row) => row.split('=')).forEach(([key, value]) => {
            let mapValue: number | string | boolean | string[] = value;
            // 处理数组 Array
            const matches = value ? value.match(/\{(.*?)\}/) : null;
            if (matches) {
              mapValue = matches[1].split(',').map(str => str.replace(/"/g, ''));
            }
            // 处理布尔值 boolean
            if (mapValue === 'TRUE') mapValue = true;
            if (mapValue === 'FALSE') mapValue = false;
            // 处理数值类型 Number
            if (typeof mapValue === 'string' && !isNaN(parseFloat(mapValue)))
              mapValue = Number(mapValue).valueOf();
            key && map.set(key, mapValue);
          });
          return Object.fromEntries(map);
        }).filter(Boolean) as unknown as Printer[];
        resolve(printers);
      });
    })
  }
myteril commented 7 months ago

It seems that you've derived your own version from the code. It's allowed because the repository is licensed with Apache License 2.0. However the issue is not about the original code, thus I cannot help you about it. You should correct your own code by yourself.

CloudWoR commented 7 months ago

Sorry, there was an error in the content that GPT translated for me. What I meant was that your code would encounter issues when running locally, that is, when processing Array types, using the JSON. parse() method would result in errors. Therefore, I rewrote this method.