Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
file-system-access
Advanced tools
File System Access API implementation (ponyfill) with pluggable storage adapters via IndexedDB, Cache API, in-memory etc.
This is an implementation of the File System Access specification. It is a ponyfill that uses the native browser implementation when available and falls back to a custom one otherwise. It also includes several storage adapters which can be used in the browser, but also in other environments, such as NodeJS or Deno.
The library roughly contains the following:
showDirectoryPicker
, showOpenFilePicker
and showSaveFilePicker
, with fallbacks to regular input elements.FileSystemFileHandle
and FileSystemDirectoryHandle
interfaces.FileSystemWritableFileStream
to truncate and write data.navigator.storage.getDirectory()
(getOriginPrivateDirectory
) which can read & write data to and from several sources called adapters, not just the browser sandboxed file systemDataTransferItem.prototype.getAsFileSystemHandle()
This package builds upon native-file-system-adapter, adding several bug fixes, updates for compliance with the latest spec, browser support improvements (especially Safari), support for bundlers, stricter error handling and more. It is fully rewritten in TypeScript and provides type-safe declarations out-of-the-box.
When getOriginPrivateDirectory
is called with no arguments, the browser's native sandboxed file system is used, just like calling navigator.storage.getDirectory()
.
Optionally, a file system backend adapter can be provided as an argument. This ponyfill ships with a few backends built in:
node
: Uses NodeJS's fs
moduledeno
: Interact with filesystem using Denosandbox
(deprecated): Uses requestFileSystem. Only supported in Chromium-based browsers using the Blink
engine.indexeddb
: Stores files into the browser's IndexedDB
object database.memory
: Stores files in-memory. Thus, it is a temporary file store that clears when the user navigates away.cache
: Stores files with the browser's Cache API in request/response pairs.You can even load in your own underlying adapter and get the same set of API's by implementing the FileSystemFileHandleAdapter and FileSystemFolderHandleAdapter interfaces
The API is designed in such a way that it can work with or without the ponyfill if you choose to remove or add this.
It's not trying to interfere with the changing spec by using other properties that may conflict with the feature changes to the spec.
You can directly import the module using an absolute URL:
<script type="module">
import { getOriginPrivateDirectory } from 'https://cdn.jsdelivr.net/npm/file-system-access/lib/es2018.js'
// Get a directory handle for a sandboxed virtual file system
// same as calling navigator.storage.getDirectory()
const dirHandle1 = await getOriginPrivateDirectory()
// or use an adapter (see adapters table above for a list of available adapters)
const dirHandle2 = await getOriginPrivateDirectory(import('https://cdn.jsdelivr.net/npm/file-system-access/lib/adapters/<adapterName>.js'))
</script>
Works in Node.JS v14.8+ or in the browser, with a module bundler such as Webpack.
npm i file-system-access
import { getOriginPrivateDirectory } from 'file-system-access'
import indexedDbAdapter from 'file-system-access/lib/adapters/indexeddb.js'
import nodeAdapter from 'file-system-access/lib/adapters/node.js'
const dirHandle = await getOriginPrivateDirectory(indexedDbAdapter)
const nodeDirHandle = await getOriginPrivateDirectory(nodeAdapter, './real-dir')
You can get a directory handle to a sandboxed virtual file system using the getOriginPrivateDirectory
function.
This is a legacy name introduced by an older Native File System
specification and is kept for simplicity.
It is equivalent to the navigator.storage.getDirectory()
method introduced by the later File System Access spec.
import { getOriginPrivateDirectory, support } from 'file-system-access'
// Uses only native implementation - same as calling navigator.storage.getDirectory()
if (support.adapter.native) {
handle = await getOriginPrivateDirectory()
}
// Blinks old sandboxed api
if (support.adapter.sandbox) {
handle = await getOriginPrivateDirectory(import('file-system-access/lib/adapters/sandbox.js'))
}
// fast in-memory file system
handle = await getOriginPrivateDirectory(import('file-system-access/lib/adapters/memory.js'))
// Using indexDB
handle = await getOriginPrivateDirectory(import('file-system-access/lib/adapters/indexeddb.js'))
// Store things in the new Cache API as request/responses (bad at mutating data)
if (support.adapter.cache) {
handle = await getOriginPrivateDirectory(import('file-system-access/lib/adapters/cache.js'))
}
// Node only variant:
handle = await getOriginPrivateDirectory(import('file-system-access/lib/adapters/memory.js'))
handle = await getOriginPrivateDirectory(import('file-system-access/lib/adapters/node.js'), './starting-path')
// Deno only variant:
handle = await getOriginPrivateDirectory(import('file-system-access/src/adapters/memory.js'))
handle = await getOriginPrivateDirectory(import('file-system-access/src/adapters/deno.js'), './starting-path')
import { showDirectoryPicker, showOpenFilePicker } from 'file-system-access'
// The polyfilled (file input) version will turn into a memory adapter
// You will have read & write permission on the memory adapter,
// you might want to transfer (copy) the handle to another adapter
const [fileHandle] = await showOpenFilePicker({_preferPolyfill: boolean, ...sameOpts})
const dirHandle = await showDirectoryPicker({_preferPolyfill: boolean, ...sameOpts})
// Apply polyfill for DataTransferItem.prototype.getAsFileSystemHandle()
import { polyfillDataTransferItem } from 'file-system-access'
await polyfillDataTransferItem();
// or just use a static import
import 'file-system-access/lib/polyfillDataTransferItem.js'
window.ondrop = async evt => {
evt.preventDefault()
for (let item of evt.dataTransfer.items) {
const handle = await item.getAsFileSystemHandle()
console.log(handle)
}
}
import { showOpenFilePicker, getOriginPrivateDirectory } from 'file-system-access'
// request user to select a file
const [fileHandle] = await showOpenFilePicker({
types: [], // default
multiple: false, // default
excludeAcceptAllOption: false, // default
_preferPolyfill: false // default
})
// returns a File Instance
const file = await fileHandle.getFile()
// copy the file over to a another place
const rootHandle = await getOriginPrivateDirectory()
const fileHandle = await rootHandle.getFileHandle(file.name, { create: true })
const writable = await fileHandle.createWritable()
await writable.write(file)
await writable.close()
import { showSaveFilePicker } from 'file-system-access'
const fileHandle = await showSaveFilePicker({
_preferPolyfill: false,
suggestedName: 'Untitled.png',
types: [
{ accept: { "image/png": [ ".png" ] } },
{ accept: { "image/jpg": [ ".jpg" ] } },
{ accept: { "image/webp": [ ".webp" ] } }
],
excludeAcceptAllOption: false // default
})
// Look at what extension they have chosen
const extensionChosen = fileHandle.name.split('.').pop()
const blob = {
jpg: generateCanvasBlob({ type: 'blob', format: 'jpg' }),
png: generateCanvasBlob({ type: 'blob', format: 'png' }),
webp: generateCanvasBlob({ type: 'blob', format: 'webp' })
}[extensionChosen]
await blob.stream().pipeTo(fileHandle.createWritable())
// or
var writer = fileHandle.getWritable()
await writer.write(blob)
await writer.close()
When importing as an ES module, browsers that support dynamic imports and ES2018 features are a minimum requirement. When using a bundler, this restriction is no longer applicable.
When the directory picker falls back to input
elements, the browser must support webkitdirectory and webkitRelativePath. Because of this, support for picking directories is generally poor on Mobile browsers.
For drag and drop, the getAsFileSystemHandle()
polyfill depends on the File and Directory Entries API
support, more specifically FileSystemDirectoryEntry, FileSystemFileEntry and webkitGetAsEntry.
showDirectoryPicker
and showOpenFilePicker
will not throw any AbortError
s (e.g. user cancellations) when using a fallback input elementshowDirectoryPicker
will return a flat hierarchy when a fallback input
element is used and webkitRelativePath
is not supported (e.g. mobile Safari). This can be detected by checking if the name
attribute of the root directory handle is an empty string.showSaveFilePicker
may not actually show any prompt when using a fallback input (e.g. on Chrome the file is auto-saved to the browser's preferred download folder)Saving/downloading a file is borrowing some of ideas from StreamSaver.js. The difference is:
to set up a service worker you have to basically copy the example and register it:
navigator.serviceWorker.register('sw.js')
Without service worker you are going to write all data to the memory and download it once it closes.
Seeking and truncating won't do anything. You should be writing all data in sequential order when using the polyfilled version.
npx http-server -p 3000 .
http://localhost:3000/example/test.html
in your browser.npm run test-node
npm run test-deno
I recommend to follow up on this links for you to learn more about the API and how it works
getSystemDirectory
).file-system-access is licensed under the MIT License. See LICENSE
for details.
FAQs
File System Access API implementation (ponyfill) with pluggable storage adapters via IndexedDB, Cache API, in-memory etc.
The npm package file-system-access receives a total of 11,975 weekly downloads. As such, file-system-access popularity was classified as popular.
We found that file-system-access demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.