> adonis install @adonisjs/drive
You are viewing the legacy version of AdonisJS. Visit https://adonisjs.com for newer docs. This version will receive security patches until the end of 2021.
AdonisJs has a dedicated Drive Provider built on top of Flydrive to interact with local and remote file systems like Amazon S3.
In this guide, we learn how to set up and use the Drive Provider.
As the Drive Provider is not installed by default, we need to pull it from npm
:
> adonis install @adonisjs/drive
Next, we need to register the provider inside the start/app.js
file:
const providers = [
'@adonisjs/drive/providers/DriveProvider'
]
Driver configuration is saved inside the config/drive.js file, which is created by the adonis install command when installing the Drive Provider.
|
Here’s a basic example of how to interact with the local disk via adonis repl
:
While common operations like reading and writing remain the same across drivers, the API of a drive is mainly based upon the driver you’re using to interact with that drive’s file system.
Find if a file/directory exists or not:
const exists = await Drive.exists('unicorn.jpg')
Get file contents as a buffer or string:
const unicorn = await Drive.get('unicorn.jpg')
Create a new file with given contents (creates any missing directories):
await Drive.put('hello.txt', Buffer.from('Hello world!'))
Prepend content to a file (creates a new file if path doesn’t exist):
await Drive.prepend('hello.txt', Buffer.from('Prepended!'))
The prepend method only works with the local driver.
|
Append content to a file (creates a new file if path doesn’t exist):
await Drive.append('hello.txt', Buffer.from('Appended!'))
The append method only works with the local driver.
|
Move file from one directory to another:
await Drive.move('hello.txt', 'hi.txt')
Copy file from one directory to another:
await Drive.copy('hi.txt', 'hello.txt')
The following methods work for the s3
and spaces
drivers only.
Get S3 object for a given file (for params
info, see S3 params):
await Drive.disk('s3').getObject('unicorn.jpg')
Get url for a given file (accepts optional alternative bucket
param):
const url = Drive.disk('s3').getUrl('unicorn.jpg')
Get signed url for a given file (expiry set to 15mins
by default):
const url = await Drive.disk('s3').getSignedUrl('unicorn.jpg')