tav-media
Version:
Cross platform media editing framework
99 lines (98 loc) • 3.41 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { Http } from "./http";
export let fs;
export function setFS(fsModule) {
fs = fsModule;
}
/**
* Utils to work with file system.
*/
export class FileSystem {
/**
* Download file from url to WASM virtual file system.
* @param localPath The local path to write the data to.
* @param fetchInput The url or Request object to fetch.
* @param fetchInit The RequestInit object to modify the request.
* @returns true if success, false if failed.
*/
static download(localPath, fetchInput, fetchInit) {
return __awaiter(this, void 0, void 0, function* () {
let response;
try {
response = yield Http.fetch(fetchInput, fetchInit);
}
catch (error) {
return false;
}
if (!response.ok) {
console.error('http error', response);
return false;
}
const data = yield response.arrayBuffer();
FileSystem.writeFile(localPath, new Uint8Array(data));
return true;
});
}
/**
* Write text or binary data to WASM virtual file system.
* @param localPath The local path to write the data to.
* @param data The text or binary data to write.
*/
static writeFile(localPath, data, opts) {
if (localPath.indexOf('/') >= 0) {
this.mkdir(FileSystem.getParentDir(localPath));
}
fs.writeFile(localPath, data, opts);
}
/**
* Read text or binary data from WASM virtual file system.
* @param localPath The local path to read the data from.
* @returns File content as text or binary data.
*/
static readFile(localPath) {
return fs.readFile(localPath);
}
/**
* Get parent directory of a path.
* @param path Any path.
* @returns The parent directory of the path.
*/
static getParentDir(path) {
const folders = path.replace(/\\/ig, '/').split('/');
if (folders.length > 1) {
folders.splice(folders.length - 1, 1);
}
// fix '/123' => ['','123'] => [''] => '', should be '/'
if (folders.length === 0 && folders[0] === '') {
folders[0] = '/';
}
return folders.join('/');
}
/**
* Make directory in WASM virtual file system.
* @param path Directory path.
* @returns void
*/
static mkdir(path) {
try {
fs.stat(path);
return;
}
catch (error) {
// not exist
}
const parent = this.getParentDir(path);
if (parent !== path) {
this.mkdir(parent);
}
fs.mkdir(path);
}
}