Welcome to mirror list, hosted at ThFree Co, Russian Federation.

basic.js « test « fs-write-stream-atomic « node_modules - github.com/npm/cli.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c68c7315aa2d58b733fde111af904da6424d5283 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
var test = require('tap').test
var writeStream = require('../index.js')
var fs = require('fs')
var path = require('path')

test('basic', function (t) {
  // open 10 write streams to the same file.
  // then write to each of them, and to the target
  // and verify at the end that each of them does their thing
  var target = path.resolve(__dirname, 'test.txt')
  var n = 10

  var streams = []
  for (var i = 0; i < n; i++) {
    var s = writeStream(target)
    s.on('finish', verifier)
    streams.push(s)
  }

  var verifierCalled = 0
  function verifier () {
    if (++verifierCalled < n) return
    // make sure that one of the atomic streams won.
    var res = fs.readFileSync(target, 'utf8')
    var lines = res.trim().split(/\n/)
    lines.forEach(function (line) {
      var first = lines[0].match(/\d+$/)[0]
      var cur = line.match(/\d+$/)[0]
      t.equal(cur, first)
    })

    var resExpr = /^first write \d+\nsecond write \d+\nthird write \d+\nfinal write \d+\n$/
    t.similar(res, resExpr)
    t.end()
  }

  // now write something to each stream.
  streams.forEach(function (stream, i) {
    stream.write('first write ' + i + '\n')
  })

  // wait a sec for those writes to go out.
  setTimeout(function () {
    // write something else to the target.
    fs.writeFileSync(target, 'brutality!\n')

    // write some more stuff.
    streams.forEach(function (stream, i) {
      stream.write('second write ' + i + '\n')
    })

    setTimeout(function () {
      // Oops!  Deleted the file!
      fs.unlinkSync(target)

      // write some more stuff.
      streams.forEach(function (stream, i) {
        stream.write('third write ' + i + '\n')
      })

      setTimeout(function () {
        fs.writeFileSync(target, 'brutality TWO!\n')
        streams.forEach(function (stream, i) {
          stream.end('final write ' + i + '\n')
        })
      }, 50)
    }, 50)
  }, 50)
})

test('cleanup', function (t) {
  fs.readdirSync(__dirname).filter(function (f) {
    return f.match(/^test.txt/)
  }).forEach(function (file) {
    fs.unlinkSync(path.resolve(__dirname, file))
  })
  t.end()
})