@ -226,3 +226,58 @@ exports.checkSpawnSyncRet = function(ret) {
assert . strictEqual ( ret . status , 0 ) ;
assert . strictEqual ( ret . error , undefined ) ;
} ;
var etcServicesFileName = path . join ( '/etc' , 'services' ) ;
if ( process . platform === 'win32' ) {
etcServicesFileName = path . join ( process . env . SystemRoot , 'System32' , 'drivers' ,
'etc' , 'services' ) ;
}
/ *
* Returns a string that represents the service name associated
* to the service bound to port "port" and using protocol "protocol" .
*
* If the service is not defined in the services file , it returns
* the port number as a string .
*
* Returns undefined if / e t c / s e r v i c e s ( o r i t s e q u i v a l e n t o n n o n - U N I X
* platforms ) can ' t be read .
* /
exports . getServiceName = function getServiceName ( port , protocol ) {
if ( port == null ) {
throw new Error ( "Missing port number" ) ;
}
if ( typeof protocol !== 'string' ) {
throw new Error ( "Protocol must be a string" ) ;
}
/ *
* By default , if a service can ' t be found in / e t c / s e r v i c e s ,
* its name is considered to be its port number .
* /
var serviceName = port . toString ( ) ;
try {
/ *
* I ' m not a big fan of readFileSync , but reading / etc / services asynchronously
* here would require implementing a simple line parser , which seems overkill
* for a simple utility function that is not running concurrently with any
* other one .
* /
var servicesContent = fs . readFileSync ( etcServicesFileName ,
{ encoding : 'utf8' } ) ;
var regexp = util . format ( '^(\\w+)\\s+\\s%d/%s\\s' , port , protocol ) ;
var re = new RegExp ( regexp , 'm' ) ;
var matches = re . exec ( servicesContent ) ;
if ( matches && matches . length > 1 ) {
serviceName = matches [ 1 ] ;
}
} catch ( e ) {
console . error ( 'Cannot read file: ' , etcServicesFileName ) ;
return undefined ;
}
return serviceName ;
}