summaryrefslogtreecommitdiff
path: root/test/parallel/test-fs-writefile-with-fd.js
blob: a3436006b46a0e243e39e2f728aed51944114601 (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
'use strict';

/*
 * This test makes sure that `writeFile()` always writes from the current
 * position of the file, instead of truncating the file, when used with file
 * descriptors.
 */

const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const join = require('path').join;

const tmpdir = require('../common/tmpdir');
tmpdir.refresh();

{
  /* writeFileSync() test. */
  const filename = join(tmpdir.path, 'test.txt');

  /* Open the file descriptor. */
  const fd = fs.openSync(filename, 'w');

  /* Write only five characters, so that the position moves to five. */
  assert.deepStrictEqual(fs.writeSync(fd, 'Hello'), 5);
  assert.deepStrictEqual(fs.readFileSync(filename).toString(), 'Hello');

  /* Write some more with writeFileSync(). */
  fs.writeFileSync(fd, 'World');

  /* New content should be written at position five, instead of zero. */
  assert.deepStrictEqual(fs.readFileSync(filename).toString(), 'HelloWorld');

  /* Close the file descriptor. */
  fs.closeSync(fd);
}

{
  /* writeFile() test. */
  const file = join(tmpdir.path, 'test1.txt');

  /* Open the file descriptor. */
  fs.open(file, 'w', common.mustCall((err, fd) => {
    assert.ifError(err);

    /* Write only five characters, so that the position moves to five. */
    fs.write(fd, 'Hello', common.mustCall((err, bytes) => {
      assert.ifError(err);
      assert.strictEqual(bytes, 5);
      assert.deepStrictEqual(fs.readFileSync(file).toString(), 'Hello');

      /* Write some more with writeFile(). */
      fs.writeFile(fd, 'World', common.mustCall((err) => {
        assert.ifError(err);

        /* New content should be written at position five, instead of zero. */
        assert.deepStrictEqual(fs.readFileSync(file).toString(), 'HelloWorld');

        /* Close the file descriptor. */
        fs.closeSync(fd);
      }));
    }));
  }));
}