pje
pje

Reputation: 22747

Import a text file in Deno

Is there any way to get Deno to import a text file (using import syntax)?

e.g.:

import { body } from "./somefile.txt"

// error: Expected a JavaScript or TypeScript module, 
//   but identified a Unknown module. Importing these
//   types of modules is currently not supported.
//  Specifier: file:///foo/somefile.txt

Using tsc this would be configurable but I suspect it might just be impossible in Deno?

Upvotes: 0

Views: 730

Answers (1)

jsejcksn
jsejcksn

Reputation: 33796

Deno does not currently support loading plaintext resources using import (static or dynamic).

There is the import attributes proposal which allows for importing of different types of module resources by using the with keyword, but plaintext content is not currently supported.


Using tsc this would be configurable

The TypeScript compiler currently supports resolving JSON resources using import syntax via the compiler option resolveJsonModule, but it does not support plaintext content.

Some bundlers (e.g. esbuild, rollup, webpack) support the concept of loaders/plugins, which can override the behavior of import statements in source code. Node.js offers a similar feature: module customization hooks.

On this topic: there is a GitHub issue in the Deno repository: denoland/deno#8327 — Proposal: Module Loader API.


The standard method of loading text content in a JavaScript module is to use the text() method on a response returned by the global fetch() method:

const text = await (await fetch("./somefile.txt")).text();

Some JS runtimes offer specialized APIs in addition to the above — for example, Deno offers Deno.readTextFile and Deno.readTextFileSync:

const text = await Deno.readTextFile("./somefile.txt");

Upvotes: 3

Related Questions