index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. /**
  3. * Parse the content of a passwd file into a list of user objects.
  4. * This function ignores blank lines and comments.
  5. *
  6. * ```js
  7. * // assuming '/etc/passwd' contains:
  8. * // doowb:*:123:123:Brian Woodward:/Users/doowb:/bin/bash
  9. * console.log(parse(fs.readFileSync('/etc/passwd', 'utf8')));
  10. *
  11. * //=> [
  12. * //=> {
  13. * //=> username: 'doowb',
  14. * //=> password: '*',
  15. * //=> uid: '123',
  16. * //=> gid: '123',
  17. * //=> gecos: 'Brian Woodward',
  18. * //=> homedir: '/Users/doowb',
  19. * //=> shell: '/bin/bash'
  20. * //=> }
  21. * //=> ]
  22. * ```
  23. * @param {String} `content` Content of a passwd file to parse.
  24. * @return {Array} Array of user objects parsed from the content.
  25. * @api public
  26. */
  27. module.exports = function(content) {
  28. if (typeof content !== 'string') {
  29. throw new Error('expected a string');
  30. }
  31. return content
  32. .split('\n')
  33. .map(user)
  34. .filter(Boolean);
  35. };
  36. function user(line, i) {
  37. if (!line || !line.length || line.charAt(0) === '#') {
  38. return null;
  39. }
  40. // see https://en.wikipedia.org/wiki/Passwd for field descriptions
  41. var fields = line.split(':');
  42. return {
  43. username: fields[0],
  44. password: fields[1],
  45. uid: fields[2],
  46. gid: fields[3],
  47. // see https://en.wikipedia.org/wiki/Gecos_field for GECOS field descriptions
  48. gecos: fields[4],
  49. homedir: fields[5],
  50. shell: fields[6]
  51. };
  52. }