patwasalinguist
patwasalinguist13mo ago

Is inspecting import.meta.url a reliable way to distinguish browser and deno contexts?

I have been trying to figure out a good pattern to import JSON that will work whether called in deno or the browser. This is what I was thinking:
let data

if(import.meta.url.startsWith('file')){ // we’re in deno
let jsonstring = await Deno.readTextFile('delete.json')
data = JSON.parse(jsonstring)
} else if(import.meta.url.startsWith('http')){ // we’re in the browser
let response = await fetch('delete.json')
data = await response.json()
}

export {data}
let data

if(import.meta.url.startsWith('file')){ // we’re in deno
let jsonstring = await Deno.readTextFile('delete.json')
data = JSON.parse(jsonstring)
} else if(import.meta.url.startsWith('http')){ // we’re in the browser
let response = await fetch('delete.json')
data = await response.json()
}

export {data}
I would welcome advice as to whether this is a good approach to this problem. thanks 🙏
4 Replies
crowlKats
crowlKats13mo ago
you could just use fetch for both
patwasalinguist
patwasalinguist13mo ago
hmm. i get this if i $ deno run --allow-read import-data.js
error: Uncaught TypeError: Invalid URL: './delete.json'
let response = await fetch('./delete.json')
error: Uncaught TypeError: Invalid URL: './delete.json'
let response = await fetch('./delete.json')
in other words, i'm running it as a shell script and not a deno server, if i'm explaining that correctly hmm, this seems to work
let url = new URL('./delete.json', import.meta.url).href
let response = await fetch(url)
let data = await response.json()
let url = new URL('./delete.json', import.meta.url).href
let response = await fetch(url)
let data = await response.json()
ioB
ioB13mo ago
^ I did this at deno-gfm: https://github.com/denoland/deno-gfm/blob/main/example/main.ts basically exactly what you're proposing
patwasalinguist
patwasalinguist13mo ago
nice thanks! gotta ❤️ deno