Skip to content
Permalink
Browse files Browse the repository at this point in the history
conversion to spawn and stream
  • Loading branch information
jaw187 committed Mar 11, 2016
1 parent a4859a3 commit b99ee02
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 35 deletions.
3 changes: 1 addition & 2 deletions package.json
Expand Up @@ -10,10 +10,9 @@
"engines": {
"node": ">=4.0.0"
},
"dependencies": {},
"devDependencies": {
"code": "2.x.x",
"lab": "9.x.x"
"lab": "10.x.x"
},
"bugs": {
"url": "https://github.com/jaw187/node-traceroute/issues"
Expand Down
60 changes: 27 additions & 33 deletions traceroute.js
Expand Up @@ -18,23 +18,43 @@ module.exports = internals.Traceroute = {};

internals.Traceroute.trace = function (host, callback) {


Dns.lookup(host.toUpperCase(), (err) => {

if (err && Net.isIP(host) === 0) {
return callback(new Error('Invalid host'));
}

const command = (internals.isWin ? 'tracert -d ' : 'traceroute -q 1 -n ') + host;
Child.exec(command, (err, stdout, stderr) => {
const command = (internals.isWin ? 'tracert' : 'traceroute');
const args = internals.isWin ? ['-d', host] : ['-q', 1, '-n', host];

const traceroute = Child.spawn(command, args);

const hops = [];
let counter = 0;
traceroute.stdout.on('data', (data) => {

if (err) {
return callback(err);
++counter;
if ((!internals.isWin && counter < 2) || (internals.isWin && counter < 5)) {
return null;
}

const results = internals.parseOutput(stdout);
return callback(null, results);
const result = data.toString().replace(/\n$/,'');
if (!result) {
return null;
}

const hop = internals.parseHop(result);
hops.push(hop);
});

traceroute.on('close', (code) => {

if (callback) {
return callback(null, hops);
}
});

return traceroute;
});
};

Expand Down Expand Up @@ -96,29 +116,3 @@ internals.parseHopNix = function (line) {

return hop;
};

internals.parseOutput = function (output) {

const lines = output.split('\n');
const hops = [];

lines.shift();
lines.pop();

if (internals.isWin) {
for (let i = 0; i < lines.length; ++i) {
if (/^\s+1/.test(lines[i])) {
break;
}
}
lines.splice(0,i);
lines.pop();
lines.pop();
}

for (let i = 0; i < lines.length; ++i) {
hops.push(internals.parseHop(lines[i]));
}

return hops;
};

0 comments on commit b99ee02

Please sign in to comment.