This repository was archived by the owner on May 18, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfasta-parser.js
More file actions
85 lines (79 loc) · 2.24 KB
/
fasta-parser.js
File metadata and controls
85 lines (79 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// # fasta-parser
// > Buffer Stream parser from FASTA to JSON.
// >
// > doi: [?](?)
// > author: [Bruno Vieira](http://bmpvieira.com)
// > email: <mail@bmpvieira.com>
// > license: [MIT](https://raw.githubusercontent.com/bionode/fasta-parser/master/LICENSE)
//
// ---
//
// ## Usage
//
// $ npm install fasta-parser
//
// var parser = require('fasta-parser')
//
// var fastaData = Buffer.from ('>sequence1\n\
// ATGCACGTCACGTCAGTACTCGTCAGTAC\n\
// >sequence2\n\
// CAGTCCTACTGCATGCATGCATGCATGCATCGATGCATGTCGACTGCATGCATGC\n')
//
// var parser = fasta()
// parser.on('data', function(data) {
// console.log(JSON.parse(data.toString()))
// })
// parser.write(fastaData)
// parser.end()
// // { id: 'sequence1',
// // seq: 'ATGCACGTCACGTCAGTACTCGTCAGTAC' }
// // { id: 'sequence2',
// // seq: 'CAGTCCTACTGCATGCATGCATGCATGCATCGATGCATGTCGACTGCATGCATGC' }
//
// For a more useful API, check the dependent module:
//
// [bionode-fasta](http://github.com/bionode/bionode-fasta)
var through = require('through2')
var split = require('split')
var pumpify = require('pumpify')
var BufferList = require('bl')
module.exports = function () {
return pumpify(split(), parser())
}
function parser () {
var cacheBuf
var openID = Buffer.from('{"id":"')
var closeIDOpenSeq = Buffer.from('","seq":"')
var closeSeq = Buffer.from('"}\n')
var stream = through(transform, flush)
return stream
function transform (buf, enc, next) {
if (buf[0] === 62) { // If line starts with '>', this is an ID
if (cacheBuf) { // If a previous object is in cache, push it
cacheBuf.append(closeSeq)
this.push(cacheBuf.slice())
}
var id = buf.toString().slice(1).trim().replace(/"/g, '\\"')
cacheBuf = new BufferList()
cacheBuf.append(openID)
cacheBuf.append(id)
cacheBuf.append(closeIDOpenSeq)
} else {
if (buf.length === 0) {
// Ignore empty
} else if (!cacheBuf) {
this.emit('error', {msg: 'Failed fasta parsing', buf: buf})
} else {
cacheBuf.append(buf)
}
}
next()
}
function flush () {
if (cacheBuf) {
cacheBuf.append(closeSeq)
this.push(cacheBuf.slice())
}
this.push(null)
}
}