I am sure this is a fundamentally misunderstanding of how streams work, but I am banging my head on the wall.
I have some sensor data in json format that I want to append to a csv file using the csv-write-stream package. The data is sent as a post request to a node server with the intention of having it appended to a csv file. It writes a line to the csv file fine the first time, but then I get "Error: write after end" error if I try to send another post request.
function write_csv(obj) {
writer.pipe(fs.createWriteStream('tides.csv', { flags: 'a' }));
writer.write(obj);
writer.end();
};
If I comment out "writer.end()" it works fine, but won't this eventually throw a memory error? If so, what is the correct way to append to a csv file and avoid this error?
EDIT: Here is the entire server.js file
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const exphbs = require('express-handlebars');
const fs = require('fs');
const csvWriter = require('csv-write-stream');
const writer = csvWriter({ sendHeaders: false });
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
app.set('port', (process.env.PORT || 3000));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.get('/', function (req, res) {
res.render('home')
})
app.post('/test', function (req, res, next) {
// console.log("post received");
distance = req.body.distance;
let result = test(distance);
let result_str = JSON.stringify(result);
res.end(result_str)
});
function write_csv(obj) {
writer.pipe(fs.createWriteStream('out.csv', { flags: 'a' }));
writer.write(obj);
writer.end();
};
function test(dist) {
let d = new Date();
let YYYY = d.getFullYear();
let MM = d.getMonth();
let DD = d.getDate();
let HH = d.getHours();
let mm = d.getMinutes();
let ss = d.getSeconds();
let date = YYYY + ':' + (MM + 1) + ':' + DD + ':' + HH + ':' + mm + ':' + ss;
let time_distance = { 'time': date, 'distance': distance };
console.log(time_distance);
write_csv(time_distance);
return time_distance;
};
app.listen(app.get('port'), function () {
console.log('Sever started on port ' + app.get('port'));
})