diff --git a/open/wrapper/index.js b/open/wrapper/index.js index d46e3b1..9740f7d 100644 --- a/open/wrapper/index.js +++ b/open/wrapper/index.js @@ -301,6 +301,7 @@ globalThis.JSProxyStream = function () { this.error = async function (err) {}; }; + /** * Creates a new JSFile object with the specified path. * @@ -327,6 +328,12 @@ globalThis.JSFile = function (path) { this.open = async function (mode) { const file = this; return await new Promise((resolve, reject) => { + if (mode == 'w' || mode == 'a') { + const directoryPath = dirname(file._path); + if (!fs.existsSync(directoryPath)) { + fs.mkdirSync(directoryPath, { recursive: true }); + } + } fs.open(file._path, mode, null, (e, f) => { if (!e) file.fd = f; if (file.fd) resolve(true); @@ -373,6 +380,13 @@ globalThis.JSFile = function (path) { }); }; + /** + * Flush buffers to disk. + */ + this.flush = async function () { + return; + }; + /** * Closes the file descriptor. * @@ -391,7 +405,7 @@ globalThis.JSFile = function (path) { * Moves the file to a new path. * * @param {string} newPath - The new path where the file will be moved. - * @return {boolean} Returns true if the file was successfully moved, otherwise returns false. + * @return {Promise} A promise that resolves with `true` if the file was successfully moved, otherwise returns false. */ this.move = async function (newPath) { const file = this; @@ -403,6 +417,22 @@ globalThis.JSFile = function (path) { }); }; + /** + * Copies the file to a new path. + * + * @param {string} newPath - The path of the new location where the file will be copied. + * @return {Promise} A promise that resolves with `true` if the file is successfully copied, and `false` otherwise. + */ + this.copy = async function (newPath) { + const file = this; + return await new Promise((resolve, reject) => { + fs.copyFile(file._path, newPath, (err) => { + if (!err) resolve(true); + else resolve(false); + }); + }); + }; + /** * Deletes the file associated with this object. * @@ -415,6 +445,36 @@ globalThis.JSFile = function (path) { }); }); }; + + /** + * Checks if the file exists. + * + * @return {Promise} A promise that resolves to a boolean value indicating whether the file exists or not. + */ + this.exist = async function () { + const file = this; + return await new Promise((resolve, reject) => { + fs.exists(file._path, (stat) => { + resolve(stat); + }); + }); + }; + + /** + * @returns the file length + */ + this.size = async function () { + const file = this; + return await new Promise((resolve, reject) => { + fs.stat(file._path, (err, stat) => { + if (err) { + resolve(0); + } else { + resolve(stat.size); + } + }); + }); + }; }; globalThis.url2Proxy = async function (type, url, headers) {