Web APIs by example

This is a collection of snippets to help you get familiar with Beaker’s APIs. You can read more about the APIs here: DatArchive, permissions.

Create a site

var archive = await DatArchive.create({
  title: 'My Site',
  description: 'Where I put my files'
// => dat://da2ce4..dc/

Write a file

await archive.writeFile('/hello.txt', 'world')
await archive.writeFile('/image.png', myArrayBuffer)
await archive.writeFile('/image.png', myBase64, 'base64')

Read a file

var helloTxt = await archive.readFile('/hello.txt')
// => String
var imagePng = await archive.readFile('/image.png', 'binary')
// => ArrayBuffer

Create a directory

await archive.mkdir('/subdir'))

List files

var files = await archive.readdir('/')
console.log(files) // => ['index.html', 'js']
var files = await archive.readdir('/', {recursive: true})
console.log(files) // => ['index.html', 'js', 'js/index.js']

Check if a file exists

try {
  var st = await archive.stat('/foo.txt')
  // does exist
} catch (e) {
  // does not exist

Get the last-modified time of a file

The ctime is the file creation-time, and mtime is the last-modified time. Note: ctime and mtime can be edited by the file’s author and may be incorrect.

var st = await archive.stat('/hello.txt')
/* => {
  ctime: 1477267871000,
  mtime: 1477267871000,
} */

Read a binary file

// arraybuffer:
var arrayBuf = await archive.readFile('/picture.png')
var blob = new Blob([arrayBuf], {type: 'image/png'})
var src = URL.createObjectURL(blob)
document.querySelector('img').src = src

// base64:
var base64 = await archive.readFile(picUrl, 'base64')
var src = 'data:image/png;base64,'+base64
document.querySelector('img').src = src

Write a binary file

var orgUrl = archive.url + '/picture.png'
var res = await fetch(orgUrl)

// arraybuffer:
var arrayBuf = await res.arrayBuffer()
await archive.writeFile('/picture_copy.png', arrayBuf)

// base64:
var base64 = convertBufToBase64(arrayBuf)
await archive.writeFile('/picture_copy.png', base64, 'base64')

Request network access to a host

var res = await navigator.permissions.request({
  name: 'network',
  hostname: 'github.com'
// => 'granted'

Request network access to all hosts

var res = await navigator.permissions.request({
  name: 'network',
  hostname: '*'
// => 'granted'