如何将 xlsx 转换为 json 从 ftp 读取它?

How to convert xlsx to json reading it from an ftp?

我正在尝试从 ftp 下载 .xlsx 文件,并使用 XSLX 模块将其转换为 .json,然后将其写入文件。所有这些都使用 Node.js

const fs = require('fs');
const Client = require('ftp');
const XLSX = require('xlsx');

const c = new Client();

c.connect({
  host: '***.***.***.**',
  user: '*********',
  password: '*********',
});

c.on('ready', () => {
  c.get('/market.xlsx', (err, stream) => {
    if (err) throw err;
    stream.once('close', () => c.end());
    
    let content = '';
    stream.on('data', (chunk) => {
      content += chunk;
    });
    stream.on('end', () => {
      //I guess something is wrong here
      const json = XLSX.utils.sheet_to_json(content);
      fs.writeFileSync(
        './files/market-to-json.json',
        JSON.stringify(json, null, 2),
        'utf-8'
      );
    });
  });
});

我在.json

的实际输出
[]

我为此苦苦挣扎了一个星期,找不到解决办法,请帮忙!

sheet_to_json需要一个worksheet对象,所以其实需要先读取内容,然后传递想要的worksheet

尝试将内容作为缓冲区读取,然后在流完成后传递所需的 sheet:

  c.get('/market.xlsx', (err, stream) => {
    if (err) throw err;
    stream.once('close', () => c.end());
    
    let content = [];
    stream.on('data', (chunk) => {
      content.push(chunk);
    });
    stream.on('finish', () => {
      
      const excel = XLSX.read(Buffer.concat(content), {type:'buffer'})
      
      const json = XLSX.utils.sheet_to_json(excel.Sheets[excel.SheetNames[0]]);

      fs.writeFileSync(
        './files/market-to-json.json',
        JSON.stringify(json, null, 2),
        'utf-8'
      );
    });
  });