Last active
July 27, 2017 19:28
-
-
Save joaoneto/5695616 to your computer and use it in GitHub Desktop.
Track para os correios
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var parseTrack = function (data) { | |
var trackLines = data.replace(/[\r\n]/g, '').replace(/<\/tr>/gi, '</tr>\n').match(/<tr.*?>(.*)<\/tr>/gi); | |
trackLines.shift(); | |
var parsed = [], parts = []; | |
var length = trackLines.length; | |
var details, date, track; | |
while (length--) { | |
parts = trackLines[length].split(/<.*?>/).filter(function (v) { return v !== '' }); | |
if (parts.length === 1) { | |
details = parts[0].trim(); | |
} else { | |
date = parts[0].replace(/(\d{2})\/(\d{2})\/(\d{4})(\s+?.*?)/, '$3-$2-$1$4'); | |
track = { | |
date: new Date(date), | |
local: parts[1].trim(), | |
status: parts[2].toLowerCase().trim() | |
}; | |
if (details) track.details = details; | |
parsed.push(track); | |
details = null; | |
} | |
} | |
return parsed.reverse(); | |
}; | |
var track = module.exports = function (objectId, callback) { | |
var buffer; | |
var options = { | |
hostname: 'websro.correios.com.br', | |
path: '/sro_bin/txect01$.QueryList?P_LINGUA=001&P_TIPO=001&P_COD_UNI=' + objectId | |
}; | |
var req = http.request(options, function (res) { | |
res.setEncoding('binary'); | |
res.on('data', function (chunk) { | |
buffer = chunk.toString('utf8'); | |
}); | |
res.on('end', function () { | |
var data = parseTrack(buffer); | |
callback(null, data); | |
}); | |
}); | |
req.on('error', function (e) { | |
callback(e); | |
}); | |
req.end(); | |
}; | |
// try it, call node correios.js TE123456789BR | |
// track(process.argv[2], function (err, data) { | |
// console.log(data); | |
// }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment