File System

AdonisJs has a 1st party provider built on top of Flydrive to interact with local disk and remote file systems like s3. In this guide, we learn about setting up the provider and making use of it.

Setup

Since the drive provider is not installed by default, we need to pull it from npm.

Installing the provider via adonis command will setup the config file for you automatically.
adonis install @adonisjs/drive

Next, we need to register the provider inside start/app.js file.

const providers = [
  '@adonisjs/drive/providers/DriveProvider'
]

Available drivers

The only available drivers shipped by default are:

  1. S3 ( s3 )

  2. Local ( local )

Basic Example

Let’s start with the basic example of interacting the local file system using the Adonis repl.

Drive dlcc3v

Drive API

The API of the drive is majorly based upon driver you are using to interact with the file system. However, for common operations like write and read, it remains the same.

exists(relativePath)

Find if a file/directory exists or not.

const exists = await Drive.exists('unicorn.jpg')

get(relativePath, encoding = utf-8)

Get file contents as a buffer or a string.

const unicorn = await Drive.get('unicorn.jpg')

getStream(relativePath)

Get file as a stream

Drive.getStream('hello.txt')

put(relativePath, content, options = {})

Create a new file with given contents. This method will create the missing directories.

await Drive.put('hello.txt', Buffer.from('Hello world!'))

prepend(relativePath, content, options = {})

Prepend content to an exisiting file. If file is missing, this method will create a new file.

Only works with local driver
await Drive.prepend('hello.txt', Buffer.from('Hello everyone!'))

append(relativePath, content, options = {})

Append content to an exisiting file. If file is missing, this method will create a new file.

Only works with local driver
await Drive.append('hello.txt', Buffer.from('Hello everyone!'))

delete(relativePath)

Remove existing file.

await Drive.delete('hello.txt')

move(src, dest, options = {})

Move file from one directory to another.

await Drive.move('hello.txt', 'hi.txt')

copy(src, dest, options = {})

Copy file from one directory to another.

await Drive.copy('hi.txt', 'hello.txt')

S3 specific methods

Below is the list of methods that works for s3 driver only.

getObject(location, params)

Get s3 object for a given file. Params is the list of S3 params.

await Drive.disk('s3').getObject('unicorn.jpg')

getUrl(location, [bucket])

Get URL to a file from the s3 bucket. Optionally you can define a different bucket too.

const url = Drive.disk('s3').getUrl('unicorn.jpg')

getSignedUrl(location, expiry = 900, params)

Get signed url to a given file. By default the expiry is set to 15mins.

const url = await Drive.disk('s3').getSignedUrl('unicorn.jpg')