aboutsummaryrefslogtreecommitdiff
path: root/test/bun.js/bun-write.test.js
blob: 68e221d51976ff4f246e6a0cc9f49febecfabfc8 (plain) (blame)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import fs from "fs";
import { it, expect, describe } from "bun:test";
import path from "path";
import { gcTick, withoutAggressiveGC } from "./gc";

it("Bun.write blob", async () => {
  await Bun.write(Bun.file("/tmp/response-file.test.txt"), Bun.file(path.join(import.meta.dir, "fetch.js.txt")));
  await gcTick();
  await Bun.write(Bun.file("/tmp/response-file.test.txt"), "blah blah blha");
  await gcTick();
  await Bun.write(Bun.file("/tmp/response-file.test.txt"), new Uint32Array(1024));
  await gcTick();
  await Bun.write("/tmp/response-file.test.txt", new Uint32Array(1024));
  await gcTick();
  expect(await Bun.write(new TextEncoder().encode("/tmp/response-file.test.txt"), new Uint32Array(1024))).toBe(
    new Uint32Array(1024).byteLength,
  );
  await gcTick();
});

describe("large file", () => {
  const fixtures = [
    [
      `/tmp/bun-test-large-file-${Date.now()}.txt`,
      "https://www.iana.org/assignments/media-types/media-types.xhtml,".repeat(10000),
    ],
  ];

  for (const [filename, content] of fixtures) {
    it(`write ${filename} ${content.length} (text)`, async () => {
      try {
        unlinkSync(filename);
      } catch (e) {}
      await Bun.write(filename, content);
      expect(await Bun.file(filename).text()).toBe(content);

      try {
        unlinkSync(filename);
      } catch (e) {}
    });

    it(`write ${filename}.bytes ${content.length} (bytes)`, async () => {
      try {
        unlinkSync(filename + ".bytes");
      } catch (e) {}
      var bytes = new TextEncoder().encode(content);
      const written = await Bun.write(filename + ".bytes", bytes);
      expect(written).toBe(bytes.byteLength);
      expect(new Buffer(await Bun.file(filename + ".bytes").arrayBuffer()).equals(bytes)).toBe(true);

      try {
        unlinkSync(filename + ".bytes");
      } catch (e) {}
    });

    it(`write ${filename}.blob ${content.length} (Blob)`, async () => {
      try {
        unlinkSync(filename + ".blob");
      } catch (e) {}
      var bytes = new Blob([content]);
      await Bun.write(filename + ".blob", bytes);
      expect(await Bun.file(filename + ".blob").text()).toBe(content);

      try {
        unlinkSync(filename + ".blob");
      } catch (e) {}
    });
  }
});

it("Bun.file not found returns ENOENT", async () => {
  try {
    await gcTick();
    await Bun.file("/does/not/exist.txt").text();
    await gcTick();
  } catch (exception) {
    expect(exception.code).toBe("ENOENT");
  }
  await gcTick();
});

it("Bun.write('out.txt', 'string')", async () => {
  for (let erase of [true, false]) {
    if (erase) {
      try {
        fs.unlinkSync(path.join("/tmp", "out.txt"));
      } catch (e) {}
    }
    await gcTick();
    expect(await Bun.write("/tmp/out.txt", "string")).toBe("string".length);
    await gcTick();
    const out = Bun.file("/tmp/out.txt");
    await gcTick();
    expect(await out.text()).toBe("string");
    await gcTick();
    expect(await out.text()).toBe(fs.readFileSync("/tmp/out.txt", "utf8"));
    await gcTick();
  }
});

it("Bun.file -> Bun.file", async () => {
  try {
    fs.unlinkSync(path.join("/tmp", "fetch.js.in"));
  } catch (e) {}
  await gcTick();
  try {
    fs.unlinkSync(path.join("/tmp", "fetch.js.out"));
  } catch (e) {}
  await gcTick();
  const file = path.join(import.meta.dir, "fetch.js.txt");
  await gcTick();
  const text = fs.readFileSync(file, "utf8");
  fs.writeFileSync("/tmp/fetch.js.in", text);
  await gcTick();
  {
    const result = await Bun.write(Bun.file("/tmp/fetch.js.out"), Bun.file("/tmp/fetch.js.in"));
    await gcTick();
    expect(await Bun.file("/tmp/fetch.js.out").text()).toBe(text);
    await gcTick();
  }

  {
    await Bun.write(Bun.file("/tmp/fetch.js.in").slice(0, (text.length / 2) | 0), Bun.file("/tmp/fetch.js.out"));
    expect(await Bun.file("/tmp/fetch.js.in").text()).toBe(text.substring(0, (text.length / 2) | 0));
  }

  {
    await gcTick();
    await Bun.write("/tmp/fetch.js.in", Bun.file("/tmp/fetch.js.out"));
    await gcTick();
    expect(await Bun.file("/tmp/fetch.js.in").text()).toBe(text);
  }
});

it("Bun.file", async () => {
  const file = path.join(import.meta.dir, "fetch.js.txt");
  await gcTick();
  expect(await Bun.file(file).text()).toBe(fs.readFileSync(file, "utf8"));
  await gcTick();
});

it("Bun.file empty file", async () => {
  const file = path.join(import.meta.dir, "emptyFile");
  await gcTick();
  const buffer = await Bun.file(file).arrayBuffer()
  expect(buffer.byteLength).toBe(0);
  await gcTick();
});

it("Bun.file as a Blob", async () => {
  const filePath = path.join(import.meta.path, "../fetch.js.txt");
  const fixture = fs.readFileSync(filePath, "utf8");
  // this is a Blob object with the same interface as the one returned by fetch
  // internally, instead of a byte array, it stores the file path!
  // this enables several performance optimizations
  var blob = Bun.file(filePath);
  await gcTick();

  // now it reads "./fetch.js.txt" from the filesystem
  // it's lazy, only loads once we ask for it
  // if it fails, the promise will reject at this point
  expect(await blob.text()).toBe(fixture);
  await gcTick();
  // BEHAVIOR CHANGE IN BUN V0.3.0 - size is never set
  // now that it's loaded, the size updates
  // expect(blob.size).toBe(fixture.length);
  // await gcTick();
  // and it only loads once for _all_ blobs pointing to that file path
  // until all references are released
  expect((await blob.arrayBuffer()).byteLength).toBe(fixture.length);
  await gcTick();

  const array = new Uint8Array(await blob.arrayBuffer());
  await gcTick();
  const text = fixture;
  withoutAggressiveGC(() => {
    for (let i = 0; i < text.length; i++) {
      expect(array[i]).toBe(text.charCodeAt(i));
    }
  });
  await gcTick();
  expect(blob.size).toBe(fixture.length);
  blob = null;
  await gcTick();
  await new Promise(resolve => setTimeout(resolve, 1));
  var blob = Bun.file(filePath);
  expect(blob.size).toBe(fixture.length);
});

it("Response -> Bun.file", async () => {
  const file = path.join(import.meta.dir, "fetch.js.txt");
  await gcTick();
  const text = fs.readFileSync(file, "utf8");
  await gcTick();
  const response = new Response(Bun.file(file));
  await gcTick();
  expect(await response.text()).toBe(text);
  await gcTick();
});

it("Bun.file -> Response", async () => {
  // ensure the file doesn't already exist
  try {
    fs.unlinkSync("/tmp/fetch.js.out");
  } catch {}
  await gcTick();
  const file = path.join(import.meta.dir, "fetch.js.txt");
  await gcTick();
  const text = fs.readFileSync(file, "utf8");
  await gcTick();
  const resp = await fetch("https://example.com");
  await gcTick();

  expect(await Bun.write("/tmp/fetch.js.out", resp)).toBe(text.length);
  await gcTick();
  expect(await Bun.file("/tmp/fetch.js.out").text()).toBe(text);
  await gcTick();
});

it("Response -> Bun.file -> Response -> text", async () => {
  await gcTick();
  const file = path.join(import.meta.dir, "fetch.js.txt");
  await gcTick();
  const text = fs.readFileSync(file, "utf8");
  await gcTick();
  const response = new Response(Bun.file(file));
  await gcTick();
  const response2 = response.clone();
  await gcTick();
  expect(await response2.text()).toBe(text);
  await gcTick();
});

it("Bun.write('output.html', '')", async () => {
  await Bun.write("/tmp/output.html", "lalalala");
  expect(await Bun.write("/tmp/output.html", "")).toBe(0);
  await Bun.write("/tmp/output.html", "lalalala");
  expect(await Bun.file("/tmp/output.html").text()).toBe("lalalala");
});

it("Bun.write(Bun.stdout, 'Bun.write STDOUT TEST')", async () => {
  expect(await Bun.write(Bun.stdout, "\nBun.write STDOUT TEST\n\n")).toBe(24);
});

it("Bun.write(Bun.stderr, 'Bun.write STDERR TEST')", async () => {
  expect(await Bun.write(Bun.stderr, "\nBun.write STDERR TEST\n\n")).toBe(24);
});

it("Bun.write(Bun.stdout, new TextEncoder().encode('Bun.write STDOUT TEST'))", async () => {
  expect(await Bun.write(Bun.stdout, new TextEncoder().encode("\nBun.write STDOUT TEST\n\n"))).toBe(24);
});

it("Bun.write(Bun.stderr, 'new TextEncoder().encode(Bun.write STDERR TEST'))", async () => {
  expect(await Bun.write(Bun.stderr, new TextEncoder().encode("\nBun.write STDERR TEST\n\n"))).toBe(24);
});

// FLAKY TEST
// Since Bun.file is resolved lazily, this needs to specifically be checked
it.skip("Bun.write('output.html', HTMLRewriter.transform(Bun.file)))", async done => {
  var rewriter = new HTMLRewriter();

  rewriter.on("div", {
    element(element) {
      element.setInnerContent("<blink>it worked!</blink>", { html: true });
    },
  });
  await Bun.write("/tmp/html-rewriter.txt.js", "<div>hello</div>");
  var input = new Response(Bun.file("/tmp/html-rewriter.txt.js"));
  var output = rewriter.transform(input);
  const outpath = `/tmp/html-rewriter.${Date.now()}.html`;
  await Bun.write(outpath, output);
  expect(await Bun.file(outpath).text()).toBe("<div><blink>it worked!</blink></div>");
  done();
});