buffer-to-hex-dump.test.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict'
  2. const tap = require('tap')
  3. const path = require('path')
  4. const { Writable } = require('stream')
  5. const { tmpdir } = require('os')
  6. const { randomUUID } = require('crypto')
  7. const { readFile, rm } = require('fs/promises')
  8. const { setTimeout } = require('timers/promises')
  9. const bufferToHexDump = require('./buffer-to-hex-dump')
  10. const input = Buffer.from([
  11. 0x00, 0x01, 0x02, 0x03, 0x04,
  12. 0x05, 0x06, 0x07, 0x08, 0x09,
  13. 0x0a, 0x0b, 0x0c
  14. ])
  15. tap.test('writes to stream', t => {
  16. const expected = [
  17. '[0x00, 0x01, 0x02, 0x03, \n',
  18. '0x04, 0x05, 0x06, 0x07, \n',
  19. '0x08, 0x09, 0x0a, 0x0b, \n',
  20. '0x0c]'
  21. ].join('')
  22. let found = ''
  23. const destination = new Writable({
  24. write (chunk, encoding, callback) {
  25. found += chunk.toString()
  26. callback()
  27. }
  28. })
  29. destination.on('finish', () => {
  30. t.equal(found, expected)
  31. t.end()
  32. })
  33. bufferToHexDump({
  34. buffer: input,
  35. prefix: '0x',
  36. separator: ', ',
  37. wrapCharacters: ['[', ']'],
  38. width: 4,
  39. closeDestination: true,
  40. destination
  41. })
  42. })
  43. tap.test('writes to file', async t => {
  44. const expected = [
  45. '00010203\n',
  46. '04050607\n',
  47. '08090a0b\n',
  48. '0c'
  49. ].join('')
  50. const destination = path.join(tmpdir(), randomUUID())
  51. t.teardown(async () => {
  52. await rm(destination)
  53. })
  54. bufferToHexDump({
  55. buffer: input,
  56. width: 4,
  57. destination
  58. })
  59. // Give a little time for the write stream to create and
  60. // close the file.
  61. await setTimeout(100)
  62. const contents = await readFile(destination)
  63. t.equal(contents.toString(), expected)
  64. })