import { Deno } from "https://deno.land/x/deno@v1.28.3/cli/tsc/dts/lib.deno.ns.d.ts";
const { seekSync } = Deno;
Synchronously seek a resource ID (rid
) to the given offset
under mode
given by whence
. The new position within the resource (bytes from the
start) is returned.
const file = Deno.openSync(
"hello.txt",
{ read: true, write: true, truncate: true, create: true },
);
Deno.writeSync(file.rid, new TextEncoder().encode("Hello world"));
// advance cursor 6 bytes
const cursorPosition = Deno.seekSync(file.rid, 6, Deno.SeekMode.Start);
console.log(cursorPosition); // 6
const buf = new Uint8Array(100);
file.readSync(buf);
console.log(new TextDecoder().decode(buf)); // "world"
file.close();
The seek modes work as follows:
// Given file.rid pointing to file with "Hello world", which is 11 bytes long:
const file = Deno.openSync(
"hello.txt",
{ read: true, write: true, truncate: true, create: true },
);
Deno.writeSync(file.rid, new TextEncoder().encode("Hello world"));
// Seek 6 bytes from the start of the file
console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.Start)); // "6"
// Seek 2 more bytes from the current position
console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.Current)); // "8"
// Seek backwards 2 bytes from the end of the file
console.log(Deno.seekSync(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2)
file.close();