Node.js将二进制文件转换为UTF8

4
我在PostgreSQL数据库中有一个以二进制格式(bytea)存储的jrmxl(Jasper报表)文件。我正在尝试读取该文件并将其转换为普通的jrmxl(XML)文件并保存到磁盘上。
以下是我目前尝试过的方法:
var fs = require('fs');
exports.saveFile = function (pg) {
  //pg is the postgres connection to query the db
  pg.query('Select data from data_file where id = 123', function (err, result) {
    if (err) {
      console.log(err);
      return;
    }

    var data = result.rows[0].data;

    //Buffer.isBuffer(data) === true

    // I can get the data here. Now I try to convert it into text
    var file = data.toString('utf8');

    fs.writeFile('report.jrxml',file, function (er) {
      if (er) {
        console.log('an error occurred while saving the file');
        return;
      }
      console.log('file saved');
    }} 
  });
}

如果我运行上面的代码,文件会被保存但是变成了二进制格式。如何将其转换为文本格式的普通xml文件,以便可以在ireport中导入?

第三个参数应该是一个对象:fs.writeFile('路径', 文件, {encoding: 'utf8'}, function...) - ndugger
谢谢您的评论,我刚刚尝试了那个方法,但是问题仍然存在。 - diokey
不是关于Jasper报告的问题,请有人移除这个标签。 - zellers
2个回答

2

你可以先尝试通过缓冲区来处理。我曾使用过这种技术将数据库 BLOBs 转换为 base64 字符串。

var fileBuffer = new Buffer( result.rows[0].data, 'binary' );
var file = fileBuffer.toString('utf8');

我在使用Dropbox JS SDK的filesDownload时遇到了问题,这个方法帮助将一个字符串从binary转换为utf-8 - doup

0
我使用 'pako' npm 包来解决这个问题:
import { connection, Message } from 'websocket';
import * as pako from 'pako';

protected async onCustomMessage(message: Message, con): Promise<void> {
    let data;
    let text;
    if (message.type === 'utf8') {
      // console.log("Received UTF8: '" + message.utf8Data + "'");
      text = message.utf8Data;
      data = JSON.parse(text);
    } else {
      const binary = message.binaryData;

      text = pako.inflate(binary, {
        to: 'string',
      });
      data = JSON.parse(text);
    }
}

npm i pako && npm i -D @types/pako
这段内容与编程有关。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接