/*
MIT License
Copyright (c) 2021 Max Kas
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _NodeFile_filePath;
import { CopyContentsOptions, CopyOptions, MoveOptions, copyFileContents } from './ifile.js';
import { NodeFileStream } from '../streams/node_file_stream.js';
import { IOException } from '../../../salmon-core/streams/io_exception.js';
import { mkdir, stat, readdir, rename, open } from 'node:fs/promises';
import { rmdirSync, unlinkSync } from 'node:fs';
import path from 'node:path';
/**
* Salmon real local filesystem implementation for node js. This can be used only with node js.
*/
export class NodeFile {
/**
* Instantiate a real file represented by the filepath provided.
* @param {string} path The filepath.
*/
constructor(path) {
_NodeFile_filePath.set(this, void 0);
__classPrivateFieldSet(this, _NodeFile_filePath, path, "f");
}
/**
* Create a directory under this directory.
* @param {string} dirName The name of the new directory.
* @returns {Promise<IFile>} The newly created directory.
*/
async createDirectory(dirName) {
let nDirPath = __classPrivateFieldGet(this, _NodeFile_filePath, "f") + NodeFile.separator + dirName;
await mkdir(nDirPath, { recursive: true });
let dotNetDir = new NodeFile(nDirPath);
return dotNetDir;
}
/**
* Create a file under this directory.
* @param {string} filename The name of the new file.
* @returns {Promise<IFile>} The newly created file.
* @throws IOException Thrown if there is an IO error.
*/
async createFile(filename) {
let nFilepath = __classPrivateFieldGet(this, _NodeFile_filePath, "f") + NodeFile.separator + filename;
let fd = await open(nFilepath, 'a');
await fd.close();
return new NodeFile(nFilepath);
}
/**
* Delete this file or directory.
* @returns {Promise<boolean>} True if deletion is successful.
*/
async delete() {
if (await this.isDirectory()) {
let files = await this.listFiles();
for (let file of files) {
await file.delete();
}
rmdirSync(__classPrivateFieldGet(this, _NodeFile_filePath, "f"));
}
else {
unlinkSync(__classPrivateFieldGet(this, _NodeFile_filePath, "f"));
}
return !await this.exists();
}
/**
* True if file or directory exists.
* @returns {Promise<boolean>} True if exists
*/
async exists() {
let stats = null;
try {
let path = this.getDisplayPath();
stats = await stat(path);
return stats.isFile() || stats.isDirectory();
}
catch (ex) { }
return false;
}
/**
* Get the path of this file. For java this is the same as the absolute filepath.
* @returns {string} The path
*/
getPath() {
return __classPrivateFieldGet(this, _NodeFile_filePath, "f");
}
/**
* Get the display path on the physical disk. For java this is the same as the filepath.
* @returns {string} The display path.
*/
getDisplayPath() {
return __classPrivateFieldGet(this, _NodeFile_filePath, "f");
}
/**
* Get the name of this file or directory.
* @returns {string} The name of this file or directory.
*/
getName() {
if (__classPrivateFieldGet(this, _NodeFile_filePath, "f") == null)
throw new Error("Filepath is not assigned");
return path.basename(__classPrivateFieldGet(this, _NodeFile_filePath, "f"));
}
/**
* Get a stream for reading the file.
* @returns {Promise<RandomAccessStream>} The stream to read from.
* @throws FileNotFoundException
*/
async getInputStream() {
let fileStream = new NodeFileStream(this, "r");
return fileStream;
}
/**
* Get a stream for writing to this file.
* @returns {Promise<RandomAccessStream>} The stream to write to.
* @throws FileNotFoundException
*/
async getOutputStream() {
let fileStream = new NodeFileStream(this, "rw");
return fileStream;
}
/**
* Get the parent directory of this file or directory.
* @returns {Promise<IFile>} The parent directory.
*/
async getParent() {
let parentFilePath = path.dirname(this.getDisplayPath());
return new NodeFile(parentFilePath);
}
/**
* True if this is a directory.
* @returns {Promise<boolean>} True if directory
*/
async isDirectory() {
let stats = await stat(this.getDisplayPath());
return stats.isDirectory();
}
/**
* True if this is a file.
* @returns {Promise<boolean>} True if file.
*/
async isFile() {
let stats = await stat(this.getDisplayPath());
return stats.isFile();
}
/**
* Get the last modified date on disk.
* @returns {Promise<number>} The last date modified
*/
async getLastDateModified() {
return await (await stat(this.getDisplayPath())).mtime.getMilliseconds();
}
/**
* Get the size of the file on disk.
* @returns {Promise<number>} The file size
*/
async getLength() {
return await (await stat(this.getDisplayPath())).size;
}
/**
* Get the count of files and subdirectories
* @returns {Promise<number>} The number of files and subdirectories
*/
async getChildrenCount() {
return (await this.listFiles()).length;
}
/**
* List all files under this directory.
* @returns {Promise<IFile[]>} The list of files.
*/
async listFiles() {
let files = [];
let lFiles = await readdir(__classPrivateFieldGet(this, _NodeFile_filePath, "f"));
for (const filename of lFiles) {
let file = new NodeFile(__classPrivateFieldGet(this, _NodeFile_filePath, "f") + NodeFile.separator + filename);
files.push(file);
}
return files;
}
/**
* Move this file or directory under a new directory.
* @param {IFile} newDir The target directory.
* @param {MoveOptions} [options] The options
* @returns {Promise<IFile>} The moved file. Use this file for subsequent operations instead of the original.
*/
async move(newDir, options) {
if (!options)
options = new MoveOptions();
let newName = options.newFilename ? options.newFilename : this.getName();
if (newDir == null || !await newDir.exists())
throw new IOException("Target directory does not exists");
let newFile = await newDir.getChild(newName);
if (newFile && await newFile.exists())
throw new IOException("Another file/directory already exists");
let nFilePath = newDir.getDisplayPath() + NodeFile.separator + newName;
await rename(__classPrivateFieldGet(this, _NodeFile_filePath, "f"), nFilePath);
return new NodeFile(nFilePath);
}
/**
* Move this file or directory under a new directory.
* @param {IFile} newDir The target directory.
* @param {CopyOptions} [options] The options
* @returns {Promise<IFile | null>} The copied file. Use this file for subsequent operations instead of the original.
* @throws IOException Thrown if there is an IO error.
*/
async copy(newDir, options) {
if (!options)
options = new CopyOptions();
let newName = options.newFilename ? options.newFilename : this.getName();
if (newDir == null || !await newDir.exists())
throw new IOException("Target directory does not exists");
let newFile = await newDir.getChild(newName);
if (newFile && await newFile.exists())
throw new IOException("Another file/directory already exists");
if (await this.isDirectory()) {
let parent = await this.getParent();
if (await this.getChildrenCount() > 0 || parent == null)
throw new IOException("Could not copy directory use IFile copyRecursively() instead");
return parent.createDirectory(newName);
}
else {
newFile = await newDir.createFile(newName);
let copyContentOptions = new CopyContentsOptions();
copyContentOptions.onProgressChanged = options.onProgressChanged;
let res = await copyFileContents(this, newFile, copyContentOptions);
return res ? newFile : null;
}
}
/**
* Get the file or directory under this directory with the provided name.
* @param {string} filename The name of the file or directory.
* @returns {Promise<IFile | null>} The child
*/
async getChild(filename) {
if (await this.isFile())
return null;
let child = new NodeFile(__classPrivateFieldGet(this, _NodeFile_filePath, "f") + NodeFile.separator + filename);
return child;
}
/**
* Rename the current file or directory.
* @param {string} newFilename The new name for the file or directory.
* @returns {Promise<boolean>} True if successfully renamed.
*/
async renameTo(newFilename) {
let nfile = await this.getParent() + NodeFile.separator + newFilename;
await rename(__classPrivateFieldGet(this, _NodeFile_filePath, "f"), nfile);
__classPrivateFieldSet(this, _NodeFile_filePath, nfile, "f");
return true;
}
/**
* Create this directory under the current filepath.
* @returns {Promise<boolean>} True if created.
*/
async mkdir() {
await mkdir(__classPrivateFieldGet(this, _NodeFile_filePath, "f"), { recursive: true });
return await this.exists();
}
/**
* Reset cached properties
*/
reset() {
}
/**
* Returns a string representation of this object
* @returns {string} The string
*/
toString() {
return __classPrivateFieldGet(this, _NodeFile_filePath, "f");
}
}
_NodeFile_filePath = new WeakMap();
NodeFile.separator = "/";