Browse Source

Refactor file.js to generate and save the parsed CSV file using the correct destination path and emit the generated file name on parse.end

node10
Onja 12 months ago
parent
commit
42f53cd32e
  1. 10
      src/models/file.js
  2. 4
      src/subscribers/ioSubscriber.js

10
src/models/file.js

@ -22,7 +22,7 @@ const dest = path.join(basedir, 'public/csv');
function generateFilePath(filename) { function generateFilePath(filename) {
return { return {
filepath: path.join(dest, `${filename}-${Date.now()}.csv`), filepath: path.join(dest, `${filename}-${Date.now()}.csv`),
generatedpath: path.join('csv', `${filename}-generated-${Date.now()}.csv`), generatedpath: path.join(dest, `${filename}-generated-${Date.now()}.csv`),
}; };
} }
@ -122,6 +122,8 @@ class File {
// create a parse method which read the file and return a stream // create a parse method which read the file and return a stream
parse(columns) { parse(columns) {
const stream = new PassThrough(); const stream = new PassThrough();
const fileStream = fs.createWriteStream(this.generatedpath);
stream.pipe(fileStream);
// check if columns is valid // check if columns is valid
if (!columns || !columns.length) { if (!columns || !columns.length) {
@ -174,11 +176,15 @@ class File {
.on('error', (err) => { .on('error', (err) => {
// Emit a parse.error event with the error // Emit a parse.error event with the error
emitter.emit('parse.error', { url: this.url, filepath: this.filepath, error: err.message }); emitter.emit('parse.error', { url: this.url, filepath: this.filepath, error: err.message });
fileStream.end();
fs.unlink(this.generatedpath, () => {});
}) })
.on('end', () => { .on('end', () => {
// Emit a parse.end event with the url and filepath // Emit a parse.end event with the url and filepath
emitter.emit('parse.end', { url: this.url, filepath: this.filepath, count: count - 1 });
stream.end(); stream.end();
fileStream.end();
emitter.emit('parse.end', { url: this.url, filepath: this.filepath, count: count - 1, generated: path.basename(this.generatedpath) });
}); });
return stream; return stream;

4
src/subscribers/ioSubscriber.js

@ -31,8 +31,8 @@ const configure = (socket) => {
}); });
// Create a new listener for the parse.end event // Create a new listener for the parse.end event
emitter.on('parse.end', ({ filepath, columns, count }) => { emitter.on('parse.end', ({ filepath, columns, count, generated }) => {
socket.emit('parse.end', { message: 'Traitement terminé' }); socket.emit('parse.end', { message: 'Traitement terminé', generated });
}); });
// Create a new listener for the parse.error event // Create a new listener for the parse.error event

Loading…
Cancel
Save