从NodeJS发送大型csv文件到python

时间:2019-12-20 18:05:35

标签: python node.js

我需要从节点向python发送大型csv文件。此代码适用于小文件,但不适用于大文件。我也尝试过产卵过程。我不明白是什么问题。如果有人知道正确的代码,请共享

代码:

const express=require('express')
const app=express()    
let p = require('python-shell');
const fs = require('fs');
let filledarray=[]

fs.createReadStream('data.csv')

.pipe(csv())

.on('data', (row) => {



filledarray.push(row)

})

.on('end', () => {

   console.log('CSV file successfully processed');

});

app.get('/send',(req,res)=>{



  var options = {
       args:
       [
           JSON.stringify(filledarray)
       ]
  }
  p.PythonShell.run('hello.py', options, function  (err, results)  {

         if(err) {
           console.error(err)
         }
         else{
            console.log(results)
            res.send(results)
         }

  });

})

app.listen('5000')

错误

 Error: spawn ENAMETOOLONG at ChildProcess.spawn (internal/child_process.js:394:11) at Object.spawn 
 (child_process.js:535:9)

1 个答案:

答案 0 :(得分:0)

您正在向脚本hello.py发送大量数据作为参数,这就是为什么要获取ENAMETOOLONG的原因。

您需要更改Python脚本以从stdin接收数据,并使用pyshell.send(data);

let pyshell = new PythonShell('hello.py', { mode: 'text' });

// sends a message to the Python script via stdin
pyshell.send('hello');

您可以使用以下三种模式之一:

  • 使用文本模式交换文本行
  • 使用json模式交换JSON片段
  • 将二进制模式用于其他任何方式(数据按原样发送和接收)

在特定情况下,您可以使用json并单独发送每一行。然后,您可以在python脚本中使用以下内容,取自python-shell examples

我不认识任何蟒蛇

import sys, json

# simple JSON echo script
for line in sys.stdin:
  print(json.dumps(json.loads(line)))
let pyshell = new PythonShell('hello.py', { mode: 'json' });

fs.createReadStream('data.csv')
.pipe(csv())
.on('data', (row) => {
   pyshell.send(row);
})