如何格式化 SFTP 收到的 CSV 文件并批量推送到 Postgres。?

How to format the SFTP received CSV file and batch push into Postgres.?

我需要执行的步骤: 1. 从 SFTP 服务器获取 CSV 文件 2. 收到的文件未格式化,我尝试使用 fast-csv 解析器但无法实现。 3. Post将整个数据导入Postgres数据库。

const Pool = require('pg').Pool
const Client = require('ssh2-sftp-client');
let sftp = new Client();
    config = {
      host: '0.0.0.0',
      port: '22',
      username: 'tester',
      password: 'password',
    } 

       function storeValues() {
        console.log('calling');
        sftp.connect(config).then(() => {  
        sftp.get('/Retail Transaction Data.csv').then((data) => {
        console.log(""+data)
        **//FORMAT THE DATA FOR THE DATABASE**
        const pool = new Pool({
          user: 'postgres',
          host: 'localhost',
          database: 'retailtransaction',
          password: 'password',
          port: 5433,
        })

          // open the connection    
          let query ="INSERT INTO rt_transactions (Trans_ID, Store_Name, Store_Type, Category, Brand, Product, Cust_ID, Quantity, Rate, Amount, Trand_Dt, Months) VALUES (, , , , , , , , , , , )";
          pool.query(query, [data], (error, response) => {
            while(error){
              console.log(error.message)
            }
            console.log(response)       
          });
        });
      });  
      }

      storeValues();

我使用 pg-copy-streams 来完成这个任务。 关于这个 link 的文档足以说明一切: https://www.npmjs.com/package/pg-copy-streams

pool.connect(function (err, client, done) {
  var stream = client.query(copyTo('COPY my_table TO STDOUT CSV'))
  stream.pipe(process.stdout)
  stream.on('end', done)
  stream.on('error', done)
})