Skip to content

Commit

Permalink
feat(runtime): add truncate and truncateSync methods to Deno.File
Browse files Browse the repository at this point in the history
  • Loading branch information
caspervonb committed Apr 11, 2021
1 parent a87da4b commit a121960
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
2 changes: 2 additions & 0 deletions cli/dts/lib.deno.ns.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,8 @@ declare namespace Deno {
constructor(rid: number);
write(p: Uint8Array): Promise<number>;
writeSync(p: Uint8Array): number;
truncate(len?: number): void;
truncateSync(len?: number): Promise<void>;
read(p: Uint8Array): Promise<number | null>;
readSync(p: Uint8Array): number | null;
seek(offset: number, whence: SeekMode): Promise<number>;
Expand Down
44 changes: 44 additions & 0 deletions cli/tests/unit/file_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,47 @@ unitTest(function fileUsingNumberFileName(): void {
unitTest(function fileUsingEmptyStringFileName(): void {
testSecondArgument("", "");
});

unitTest(
{ perms: { read: true, write: true } },
function fileTruncateSyncSuccess(): void {
const filename = Deno.makeTempDirSync() + "/test_fileTruncateSync.txt";
const file = Deno.openSync(filename, {
create: true,
read: true,
write: true,
});

file.truncateSync(20);
assertEquals(Deno.readFileSync(filename).byteLength, 20);
file.truncateSync(5);
assertEquals(Deno.readFileSync(filename).byteLength, 5);
file.truncateSync(-5);
assertEquals(Deno.readFileSync(filename).byteLength, 0);

file.close();
Deno.removeSync(filename);
},
);

unitTest(
{ perms: { read: true, write: true } },
async function fileTruncateSuccess(): Promise<void> {
const filename = Deno.makeTempDirSync() + "/test_fileTruncate.txt";
const file = await Deno.open(filename, {
create: true,
read: true,
write: true,
});

await file.truncate(20);
assertEquals((await Deno.readFile(filename)).byteLength, 20);
await file.truncate(5);
assertEquals((await Deno.readFile(filename)).byteLength, 5);
await file.truncate(-5);
assertEquals((await Deno.readFile(filename)).byteLength, 0);

file.close();
await Deno.remove(filename);
},
);
9 changes: 9 additions & 0 deletions runtime/js/30_files.js → runtime/js/40_files.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
((window) => {
const core = window.Deno.core;
const { read, readSync, write, writeSync } = window.__bootstrap.io;
const { ftruncate, ftruncateSync } = window.__bootstrap.fs;
const { pathFromURL } = window.__bootstrap.util;

function seekSync(
Expand Down Expand Up @@ -87,6 +88,14 @@
return writeSync(this.rid, p);
}

truncate(len) {
return ftruncate(this.rid, len);
}

truncateSync(len) {
return ftruncateSync(this.rid, len);
}

read(p) {
return read(this.rid, p);
}
Expand Down

0 comments on commit a121960

Please sign in to comment.