Skip to content

File Storage ​

Introduction ​

@plinthjs/storage gives you one async interface for working with files, whatever is behind it. A disk is an object with methods like put, get, copy and delete, and every disk behaves the same way. Today there are two drivers: LocalDisk, which keeps files under a directory on the machine, and MemoryDisk, which keeps them in memory (ideal for tests). A FilesystemManager holds named disks so your code can ask for "the public disk" without caring how it is stored.

bash
pnpm add @plinthjs/storage

Paths are POSIX style (forward slashes) and relative to the disk's root. A leading slash is ignored, so avatars/1.png and /avatars/1.png mean the same file.

INFO

A generated app declares its disks in config/filesystems.ts: a local disk rooted at storage/app/private and a public disk rooted at storage/app/public. Those entries describe the disks; you build the disk objects shown below from them.

Creating disks ​

A local disk is confined to a root directory. Parent directories are created for you when you write.

ts
import { LocalDisk, MemoryDisk } from '@plinthjs/storage'

const local = new LocalDisk({ root: '/var/app/storage', urlBase: 'http://localhost/storage' })

await local.put('avatars/1.png', 'binary data') // creates avatars/ if needed
local.path('avatars/1.png') // => '/var/app/storage/avatars/1.png'

An in-memory disk needs no setup and disappears with the process:

ts
const memory = new MemoryDisk({ urlBase: '/storage' })

urlBase is the public URL prefix used by url() (see Generating URLs).

WARNING

A LocalDisk rejects any path that tries to leave its root (such as ../../etc/passwd) with a PathTraversalError. Do not catch it and retry with a cleaned-up path. Treat it as a bad request.

Reading and writing files ​

put writes a string or Buffer, replacing anything already there. It resolves to true. get reads the file as a string and rejects with a FileNotFoundError when it does not exist.

ts
await memory.put('logs/app.log', 'boot\n') // => true
await memory.get('logs/app.log') // => 'boot\n'

await memory.get('nope') // throws FileNotFoundError: File [nope] does not exist on this disk.

For JSON files, json() reads and parses in one step:

ts
await memory.put('data.json', JSON.stringify({ a: 1 }))
await memory.json<{ a: number }>('data.json') // => { a: 1 }

You can add to a file without rewriting it, or overwrite it explicitly:

ts
await memory.append('logs/app.log', 'ready\n')
await memory.prepend('logs/app.log', '# header\n')
await memory.get('logs/app.log') // => '# header\nboot\nready\n'

await memory.replace('data.json', '{}') // replace the contents

Checking for files ​

ts
await memory.exists('data.json') // => true
await memory.missing('nope') // => true
await memory.isFile('logs') // => false
await memory.isDirectory('logs') // => true
await memory.size('data.json') // => the size in bytes
await memory.lastModified('data.json') // => a timestamp in milliseconds

Saving uploads ​

putFile(directory, file, name?) stores a file under a directory and resolves to the path it was saved at. When you do not give a name, one is generated for you so uploads never overwrite each other.

ts
const stored = await memory.putFile('avatars', Buffer.from('png bytes'))
// => 'avatars/5d85b25df95f2a5d9fea11830b06f1e9ed1d477a' (a random 40-character name)

await memory.putFile('avatars', 'text', 'a.txt') // => 'avatars/a.txt'
await memory.putFileAs('avatars', 'text', 'b.txt') // => 'avatars/b.txt' (name is required)

The file can be a string, a Buffer, or an uploaded-file object. If the object has a hashName() method its result is used as the file name; otherwise the name is random, keeping the extension of getClientOriginalName() when it has one, or else the extension for the object's getMimeType() / getClientMimeType() (for example image/png gives .png). The object supplies its bytes through buffer() or get().

ts
await memory.putFile('uploads', {
  hashName: () => 'h.png',
  buffer: () => Buffer.from('1'),
}) // => 'uploads/h.png'

Streaming large files ​

For files you do not want in memory, use streams. writeStream consumes a readable stream; readStream gives you one.

ts
import { Readable } from 'node:stream'

await memory.writeStream('exports/report.csv', Readable.from(['id,name\n', '1,Ada\n']))

const stream = await memory.readStream('exports/report.csv')
for await (const chunk of stream) {
  process.stdout.write(chunk)
}

Copying, moving and deleting ​

ts
await memory.copy('data.json', 'backup/data.json') // => true
await memory.move('backup/data.json', 'archive/data.json') // => true
await memory.delete('archive/data.json') // => true
await memory.delete('already-gone') // => false

delete resolves to false instead of throwing when there is nothing to delete.

Working with directories ​

files() lists the files directly inside a directory; allFiles() descends into subdirectories. directories() lists the subdirectories. With no argument they start at the disk root. All return paths relative to the root.

ts
await memory.put('docs/a.md', 'a')
await memory.put('docs/guides/b.md', 'b')

await memory.files('docs') // => ['docs/a.md']
await memory.allFiles('docs') // => ['docs/a.md', 'docs/guides/b.md']
await memory.directories('docs') // => ['docs/guides']

To find files by pattern, use glob:

ts
await memory.glob('docs/*.md') // => ['docs/a.md']
await memory.glob('**/*.md') // => ['docs/a.md', 'docs/guides/b.md']

Create and remove directories explicitly when you need to:

ts
await memory.makeDirectory('empty/dir') // => true
await memory.deleteDirectory('empty') // => true (and everything inside it)

Visibility ​

Each file is either 'public' or 'private'. On a local disk this maps to file permissions (0644 for public, 0600 for private); on a memory disk it is recorded alongside the file. Files are public unless you say otherwise.

ts
await memory.put('report.pdf', 'data', { visibility: 'private' })
await memory.getVisibility('report.pdf') // => 'private'

await memory.setVisibility('report.pdf', 'public') // => true
await memory.getVisibility('report.pdf') // => 'public'

File information ​

ts
await memory.checksum('data.json') // => an MD5 hex digest by default
await memory.checksum('data.json', { algo: 'sha256' }) // => a SHA-256 hex digest
await memory.mimeType('data.json') // => 'application/json'

The MIME type is inferred from the file extension.

Generating URLs ​

url() builds the public URL for a path from the disk's urlBase. It throws an error naming the disk (Disk [public] has no urlBase configured) if the disk has no urlBase, so configure one on any disk you plan to link to. A disk registered with the manager is named after its key.

ts
const memory = new MemoryDisk({ urlBase: '/storage' })

memory.url('avatars/1.png') // => '/storage/avatars/1.png'

Temporary signed URLs ​

temporaryUrl() returns a URL that carries an expiry time and a signature. You give it the expiry (a Date or epoch milliseconds) and a secret key used to sign it.

ts
const url = memory.temporaryUrl('reports/q1.pdf', Date.now() + 60_000, { key: 'secret' })
// => '/storage/reports/q1.pdf?expires=1794409923078&signature=bf59...'

When a request arrives, verify it with verifyTemporaryUrl before serving the file. It returns false if the signature does not match the key, the URL was altered, or the expiry has passed.

ts
import { verifyTemporaryUrl } from '@plinthjs/storage'

verifyTemporaryUrl(url, { key: 'secret' }) // => true
verifyTemporaryUrl(url, { key: 'wrong' }) // => false
verifyTemporaryUrl(url, { key: 'secret', now: Date.now() + 120_000 }) // => false (expired)

createTemporaryUrl(url, expiresAt, key) signs any URL string the same way if you need it outside a disk. Keep the key out of source control, for example in your configuration and environment.

Scoped disks ​

scope(prefix) returns a disk whose paths are all relative to a subdirectory of the original. It is handy when one component owns a folder and should not need to know the full path.

ts
const avatars = memory.scope('avatars')

await avatars.put('n.txt', 'n')
await memory.exists('avatars/n.txt') // => true
await avatars.files() // => ['n.txt']

A scoped disk supports every disk method, and paths returned by files() and similar listings are relative to the scope.

Using several disks ​

FilesystemManager holds named disks and a default.

ts
import { FilesystemManager, LocalDisk, MemoryDisk } from '@plinthjs/storage'

const storage = new FilesystemManager({
  default: 'local',
  disks: {
    local: new LocalDisk({ root: '/var/app/storage' }),
    tmp: new MemoryDisk(),
  },
})

await storage.disk().put('a.txt', 'x') // the default disk
await storage.disk('tmp').put('b.txt', 'y') // a named disk

storage.addDisk('cache', new MemoryDisk())
storage.setDefault('cache')
storage.getDefaultName() // => 'cache'

storage.disk('missing') // throws Error: Filesystem disk [missing] is not configured. Known disks: ...

createFilesystemManager(config) does the same as new FilesystemManager(config).

Testing ​

The in-memory disk is a drop-in replacement for any disk. For tests, use FakeDisk, a memory disk with assertions. Create one with fake():

ts
import { fake } from '@plinthjs/storage'

const disk = fake()

await disk.put('invoices/1.pdf', 'pdf')

await disk.assertExists('invoices/1.pdf')
await disk.assertExists(['invoices/1.pdf']) // several at once
await disk.assertMissing('invoices/2.pdf')
await disk.assertCount('invoices', 1) // files directly in the directory
await disk.assertCount('invoices', 1, true) // include subdirectories

A failed assertion throws an error such as Expected [invoices/2.pdf] to exist on the disk, but it does not.

To swap a disk inside a manager for the duration of a test, call manager.fake(name?). It replaces the named disk (or the default) with a fresh FakeDisk and returns it, so code that asks the manager for that disk now gets the fake.

ts
const faked = storage.fake('local')
await storage.disk('local').put('x.txt', '1')
await faked.assertExists('x.txt')

memoryFilesystem() is a shortcut that builds a manager whose default disk is a fresh in-memory disk:

ts
import { memoryFilesystem } from '@plinthjs/storage'

const storage = memoryFilesystem()
await storage.disk().put('a', 'b')

Released under the MIT License.