NodeJS:从 sftp 服务器读取 csv 文件并将其转换为 JSON

NodeJS: Read csv file from sftp server and convert it to JSON

我正在使用 ssh2-sftp-client 读取 CSV 文件并创建 ReadableStream。然后我试图在库 csvtojson 的帮助下将这个 readableStream 转换为 Json。但是,我总是收到以下错误:

TypeError: readStream.pipe is not a function

到目前为止,这是我的代码:

let Client = require('ssh2-sftp-client');
let sftp = new Client();
var csv = require("csvtojson");

sftp.connect({
    host: 'HOST',
    port: 'PORT',
    username: 'USERNAME',
    password: 'PASSWORD'
}).then(() => {
    return sftp.get('/home/user/etc/testfile.csv');
}).then((data) => {
    csv()
        .fromStream(data)
        .subscribe(function (jsonObj) { //single json object will be emitted for each csv line
            // parse each json asynchronousely
            return new Promise(function (resolve, reject) {
                resolve()
                console.log(jsonObj);
            })
        })

}).catch((err) => {
    console.log(err, 'catch error');
});

有谁知道我是否正确使用了这两个库,或者我尝试实现的目标是否不可能?

您遇到错误,因为 sftp.get returns a <a href="https://nodejs.org/dist/latest-v11.x/docs/api/buffer.html" rel="nofollow noreferrer">Buffer</a> and you're trying to pass it to a function that expects a <a href="https://nodejs.org/dist/latest-v11.x/docs/api/stream.html" rel="nofollow noreferrer">Stream</a>.

将您的代码更改为此

let Client = require('ssh2-sftp-client');
let sftp = new Client();
var csv = require("csvtojson");

sftp.connect({
  host: 'HOST',
  port: 'PORT',
  username: 'USERNAME',
  password: 'PASSWORD'
}).then(() => {
  return sftp.get('/home/user/etc/testfile.csv');
}).then((data) => {
  csv()
    .fromString(data.toString()) // changed this from  .fromStream(data)
    .subscribe(function(jsonObj) { //single json object will be emitted for each csv line
      // parse each json asynchronously
      return new Promise(function(resolve, reject) {
        resolve()
        console.log(jsonObj);
      })
    })
}).catch((err) => {
  console.log(err, 'catch error');
});