Permalink
Browse files

Emit errors instead of exceptions when quotes are invalid.

  • Loading branch information...
1 parent 22e797c commit 1adb0fdd6a59d72082a2a38f3c67de9f3377f177 @justinlatimer justinlatimer committed Dec 4, 2010
Showing with 76 additions and 2 deletions.
  1. +14 −2 lib/csv.js
  2. +59 −0 test/quotes.js
  3. +2 −0 test/quotes/invalid.in
  4. +1 −0 test/quotes/unclosed.in
View
@@ -65,7 +65,12 @@ module.exports = function(){
flush();
})
}else{
- parse(data);
+ try{
+ parse(data);
+ }catch(e){
+ self.emit('error', e);
+ return;
+ }
}
finish();
});
@@ -74,7 +79,14 @@ module.exports = function(){
CSV.prototype.fromStream = function(readStream, options){
if(options) merge(this.readOptions,options);
var self = this;
- readStream.on('data', function(data) { parse(data) });
+ readStream.on('data', function(data) {
+ try{
+ parse(data);
+ }catch(e){
+ self.emit('error', e);
+ this.destroy();
+ }
+ });
readStream.on('error', function(error) { self.emit('error', error) });
readStream.on('end', function() {
finish();
View
@@ -84,5 +84,64 @@ module.exports = {
);
fs.unlink(__dirname+'/quotes/quoted.tmp');
});
+ },
+ 'Test unclosed quote': function(beforeExit){
+ var n = 0;
+ csv()
+ .fromPath(__dirname+'/quotes/unclosed.in',{
+ quote: '"',
+ escape: '"',
+ })
+ .toPath(__dirname+'/quotes/unclosed.tmp')
+ .on('end',function(){
+ assert.ok(false, 'end was raised');
+ })
+ .on('error',function(){
+ ++n;
+ });
+ beforeExit(function() {
+ assert.equal(1, n, 'error was not raised');
+ fs.unlink(__dirname+'/quotes/unclosed.tmp');
+ });
+ },
+ 'Test invalid quotes': function(beforeExit){
+ var n = 0;
+ csv()
+ .on('error',function(e){
+ assert.equal(e.message.split(';')[0], 'Invalid closing quote');
+ ++n;
+ })
+ .fromPath(__dirname+'/quotes/invalid.in',{
+ quote: '"',
+ escape: '"',
+ })
+ .toPath(__dirname+'/quotes/invalid.tmp')
+ .on('end',function(){
+ assert.ok(false, 'end was raised');
+ });
+ beforeExit(function() {
+ assert.equal(1, n, 'error was not raised');
+ fs.unlink(__dirname+'/quotes/invalid.tmp');
+ });
+ },
+ 'Test invalid quotes from string': function(beforeExit){
+ var n = 0;
+ csv()
+ .on('error',function(e){
+ assert.equal(e.message.split(';')[0], 'Invalid closing quote');
+ ++n;
+ })
+ .from('"",1974,8.8392926E7,""t,""',{
+ quote: '"',
+ escape: '"',
+ })
+ .toPath(__dirname+'/quotes/invalidstring.tmp')
+ .on('end',function(){
+ assert.ok(false, 'end was raised');
+ });
+ beforeExit(function() {
+ assert.equal(1, n);
+ fs.unlink(__dirname+'/quotes/invalidstring.tmp');
+ });
}
}
View
@@ -0,0 +1,2 @@
+"",1974,8.8392926E7,""t,""
+"",1974,8.8392926E7,"",""
View
@@ -0,0 +1 @@
+"",1974,8.8392926E7,"","

0 comments on commit 1adb0fd

Please sign in to comment.