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 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.
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'
]
The only available drivers shipped by default are:
S3 ( s3 )
Local ( local )
Let’s start with the basic example of interacting the local file system using the Adonis repl.
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.
Find if a file/directory exists or not.
const exists = await Drive.exists('unicorn.jpg')
Get file contents as a buffer or a string.
const unicorn = await Drive.get('unicorn.jpg')
Create a new file with given contents. This method will create the missing directories.
await Drive.put('hello.txt', Buffer.from('Hello world!'))
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 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!'))
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')
Below is the list of methods that works for s3
driver only.
Get s3 object for a given file. Params is the list of S3 params.
await Drive.disk('s3').getObject('unicorn.jpg')
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')
Get signed url to a given file. By default the expiry is set to 15mins
.
const url = await Drive.disk('s3').getSignedUrl('unicorn.jpg')