Deno 1.16 has been released.
In this article, I will write a sample on two features included in the 1.16 release of Deno.
fetch now supports fetching file URLs
Starting from 1.16, fetch can be used to read files from the local file system.
When reading a file, the path must be an absolute path starting with file://
.
The file contents are read in chunks, so it seems that file units can be used without reading them into memory.
According to the release notes, this is the best way to stream large files over HTTP.
First, I have writting a simple sample that just reads a local file.
First, prepare the file hello.txt
.
hello world!
Next, I will write a sample code using fetch.
The file path should be written as a full path, but it is omitted here.
// sample.ts
const resp = await fetch('file:///Users/~/hello.txt');
const text = await resp.text();
console.log({text});
Run this code.
deno run --allow-read sample.ts
The output will look something like this.
{ text: "hello world!\n" }
With import.meta.url
However, as mentioned in the official release notes, you can specify the path relatively by using import.meta.url
.
(If you use import.meta.url
, you can specify the file path by using the method starting with file://
, so you can specify the file path directly using this method.)
I have rewritting the above code using import.meta.url
.
import { dirname, join } from 'https://deno.land/std/path/mod.ts'
const filePath = join(dirname(import.meta.url), 'hello.txt');
const resp = await fetch(filePath);
const text = await resp.text();
console.log({text});
Please refer to the release notes for more details on the behavior.
New unstable signal listener API
It seems that a new (and unstable) API for reading OS signals has been added.
As the name "unstable" implies, it seems to be in an experimental stage and may be changed in the future, so be careful when using it.
It is said to be a replacement for the existing Deno.signals API.
I have written a simple sample code to terminate the process with Ctrl + C
.
// sample.ts
const listener = () => {
console.log("SIGINT!");
Deno.exit();
};
const sleep = (sec: number) => {
return new Promise((resolve) => setTimeout(resolve, sec * 1000));
};
Deno.addSignalListener("SIGINT", listener);
let count = 0;
for (const _ of Array(10)) {
count++;
console.log(count);
await sleep(1);
}
Deno.removeSignalListener("SIGINT", listener);
Run this code.
deno run --unstable sample.ts
In this sample, the numbers are displayed every second, and you can see that the process can be interrupted by pressing Ctrl + C
.
Latest comments (0)