读取CSV中的第一行并将其另存为字符串

时间:2018-07-09 13:23:49

标签: javascript node.js csv

我使用Node.JS和express-fileupload将文件从客户端上传到服务器。您也可以在浏览器中查看上载的文件,删除或下载它们。

某些文件是 csv文件。它还可以检测文件是否为csv。

我想在每个csv文件上传后保存第一行,并将其另存为数组或字符串或JSON 等。

这样我就可以在浏览器中显示第一行。 一个简单的,适合初学者的解决方案会很棒。

谢谢!

更新1: 这就是我尝试使用“ csv-parse”的方式:

function firstCsvRow(pCsv){    //the function for getting the FIRST ROW
    var csvData=[];                         // Array 
    fs.createReadStream('/usr/src/app/upload/' + pCsv) //here is the csv-file
        .pipe(parse(/*options:*/ {delimiter: ',', from: '0', to: '0'}))     
//I tried to add options like in the documentation of "csv-parse", like so to speak "from line 0 to line 0", so that I'll 
//get only the first row of the csv-file...

        .on('data', function(csvrow) {      // where does the 'csvrow' comes from? // I don't know what this is for
            console.log(csvrow); //also console-log shows nothing

            csvData.push(csvrow); //this should push the row into the Array.        
            console.log(csvData); //but again no log
        })

    var server = http.createServer((req,res)=>{
        res.writeHead(200,{ 'content-type': 'application/json' });
        res.end('Hi');
    })

    server.listen(8080);
}

   //where I actually USE the function for getting the FIRST ROW:
app.post('/dateiNameTemp', (req, res) => {

    var dateiNameServer = req.body.eingabeFeld1;       //here we get the name of the csv-file

        //Download csv-file  
    app.get('/' + dateiNameServer, (req, res) => {
        res.download('/usr/src/app/upload/' + dateiNameServer);

    })

    firstCsvRow(dateiNameServer);    //!!! this one causes errors...
});

毕竟,我不太了解发生了什么。当我执行代码时,它会在服务器端产生错误:

events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE :::8080
    at Object._errnoException (util.js:1022:11)
    at _exceptionWithHostPort (util.js:1044:20)
    at Server.setupListenHandle [as _listen2] (net.js:1367:14)
    at listenInCluster (net.js:1408:12)
    at Server.listen (net.js:1492:7)
    at firstCsvRow (/usr/src/app/chart1.js:235:9)
    at app.post (/usr/src/app/chart1.js:268:2)
    at Layer.handle [as handle_request] (/usr/src/app/node_modules/express/lib/router/layer.js:95:5)
    at next (/usr/src/app/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/usr/src/app/node_modules/express/lib/router/route.js:112:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ssa-deviceshadow-app@1.0.0 start: `node chart1.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ssa-deviceshadow-app@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2018-07-10T13_01_28_574Z-debug.log

1 个答案:

答案 0 :(得分:-1)

您可以使用csv-parse模块,如下所示

var http = require('http');
var fs = require('fs'); 
var parse = require('csv-parse');

var csvData=[];
fs.createReadStream(__dirname+'/data-example-1.csv')
    .pipe(parse({delimiter: ','}))
    .on('data', function(csvrow) {
        console.log(csvrow);
        //do something with csvrow
        csvData.push(csvrow);        
    })
    .on('end',function() {
      //do something wiht csvData
      console.log(csvData);
    });

var server = http.createServer((req,res)=>{
    res.writeHead(200,{ 'content-type': 'application/json' });
    res.end('Hi');
})

server.listen(8080);