Skip to content

Commit

Permalink
Merge pull request #390 from Inist-CNRS/fix-csv-export-null-undefined
Browse files Browse the repository at this point in the history
fix: 🐛 avoid to produce null with undefined value
  • Loading branch information
touv authored Dec 19, 2023
2 parents 0667dff + 14798ad commit 4b64445
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
5 changes: 4 additions & 1 deletion packages/basics/src/csv-string.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import CSV from 'csv-string';

const isNullOrUndefined = (value) => (value === undefined || value === null);

function strict(data, sep) {
const q = new RegExp('"', 'g');
let line = '';
let s = '';
Object.keys(data).forEach((key) => {
const cell = isNullOrUndefined(data[key]) ? '' : data[key];
line = line.concat(
s
.concat('"')
.concat(String(data[key]).replace(q, '""'))
.concat(String(cell).replace(q, '""'))
.concat('"'),
);
s = sep;
Expand Down
5 changes: 4 additions & 1 deletion packages/basics/test/basics.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,16 +107,19 @@ describe('test', () => {
from([
['a', 'b', 'c'],
[1, 2, 3],
[4, undefined, 6],
[null, undefined, ''],
])
.pipe(ezs('CSVObject'))
.pipe(ezs('CSVString', { format: 'strict' }))
.on('data', (chunk) => {
res.push(chunk);
})
.on('end', () => {
console.log(res);
assert.equal(3, res.length);
assert.equal('"a";"b";"c"\r\n', res[0]);
assert.equal('"1";"2";"3"\r\n', res[1]);
assert.equal('"";"";""\r\n', res[2]);
done();
});
});
Expand Down

0 comments on commit 4b64445

Please sign in to comment.