Skip to content

Instantly share code, notes, and snippets.

@lindenb
Created December 31, 2010 14:09
Show Gist options
  • Save lindenb/761033 to your computer and use it in GitHub Desktop.
Save lindenb/761033 to your computer and use it in GitHub Desktop.
translate a DNA to a protein using Node.js and an external C program
#include <stdio.h>
#include <ctype.h>
static const char* STD_GENETIC_CODE="FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG";
static int base2index(int c)
{
switch(c)
{
case 'T':case 't': return 0;
case 'C':case 'c': return 1;
case 'A':case 'a': return 2;
case 'G':case 'g': return 3;
default: return -1;
}
};
static char translate(int b1,int b2,int b3)
{
int base1= base2index(b1);
int base2= base2index(b2);
int base3= base2index(b3);
if(base1==-1 || base2==-1 || base3==-1)
{
return '?';
}
else
{
return STD_GENETIC_CODE[base1*16+base2*4+base3];
}
}
static int next_base(FILE* in)
{
int c;
while((c=fgetc(in))!=EOF)
{
if(isspace(c)) continue;
break;
}
return c;
}
int main(void)
{
while(!feof(stdin))
{
int b1=next_base(stdin);
if(b1==EOF) break;
int b2=next_base(stdin);
if(b2==EOF) break;
int b3=next_base(stdin);
if(b3==EOF) break;
fputc(
translate(b1,b2,b3),
stdout);
}
return 0;
}
/**
* Author:
* Pierre Lindenbaum
* Mail:
* [email protected]
* WWW:
* http://plindenbaum.blogspot.com
* Motivation:
* Node.js script . translate a DNA to a protein using an external C program
* Usage:
* ${nodejs.dir}/node translate.js
*/
var spawn = require('child_process').spawn
var sys = require('sys');
querystring = require('querystring');
function TranslateDna(req,res)
{
if(req.method == 'GET')
{
var params = require('url').parse(req.url,true);
if(params && params.query && params.query.dna)
{
res.writeHead(200, {'Content-type': 'text/plain'});
var child = spawn('/path/to/bin/translate',[]);
child.stdin.write(params.query.dna);
child.stdout.on('data', function (data) {
res.write(data);
});
child.stderr.on('data', function (data) {
console.log("stderr:"+data);
});
child.on('exit', function (data)
{
res.end();
});
child.stdin.end();
return;
}
}
res.writeHead(200, {'Content-type': 'text/html'});
res.end(
'<html><body><form action="/" method=\"GET\">'+
'<h1>DNA</h1>'+
'<textarea name="dna"></textarea><br/>' +
'<input type="submit" value="Submit">' +
'</form></body></html>'
);
}
http = require('http');
var nodeserver = http.createServer(TranslateDna);
nodeserver.listen(8080);
console.log('Server running at http://127.0.0.1:8080/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment