Skip to content

Instantly share code, notes, and snippets.

@bekirbakar
Last active April 6, 2023 21:05
Show Gist options
  • Save bekirbakar/cd695fc24b8d64ff348a7c5dd473d7a9 to your computer and use it in GitHub Desktop.
Save bekirbakar/cd695fc24b8d64ff348a7c5dd473d7a9 to your computer and use it in GitHub Desktop.
File Manager Utilities in Node.js

File Manager Utilities in Node.js

Features

  1. Configuration: A class that manages the application configuration.

    • Reads and updates the application configuration JSON file.
    • Saves the updated configuration to the JSON file.
  2. JsonFileManager: A class that reads and updates JSON files.

    • Reads JSON files and assigns their content to the class instance.
    • Provides a method to exclude specific keys from the JSON object.
    • Saves the updated JSON data back to the file.
  3. CopyArchiveAndUnzipSync: A function that copies an archive file and extracts its contents.

    • Copies an archive file to a specified destination folder.
    • Extracts the contents of the archive to the destination folder.
    • Deletes the copied archive file after extraction.
  4. FileManager: A class that handles common file operations.

    • Resolves folder paths.
    • Creates file paths with a given folder and extension.
    • Deletes multiple files from an array of file paths.
    • Saves JSON data to a specified folder, with an optional filename.

Usage

Import the required classes and functions from the module and use them in your Node.js project as needed.

Example usage:

const {Configuration, JsonFileManager, CopyArchiveAndUnzipSync, FileManager} = require('./file-utils');

// ...

// Use the CopyArchiveAndUnzipSync function.
CopyArchiveAndUnzipSync(source, destination)
  .then(() => console.log('File copied and extracted successfully'))
  .catch((error) => console.error(error));

// Create a new FileManager instance and use its methods.
const fileManager = new FileManager();

Dependencies

  • fs (built-in Node.js module)
  • path (built-in Node.js module)
  • unzipper (npm package)
'use strict';
const fs = require('fs');
const path = require('path');
const unZipper = require('unzipper');
const logger = require('electron-log');
/**
* Configuration class provides methods to load and update application
* configurations.
*/
class Configuration {
constructor() {
this.pathToJson = path.resolve(__dirname, 'config.json');
Object.assign(this, require(this.pathToJson));
}
/**
* Updates the configuration file with the current Configuration instance
* values.
*/
update() {
fs.writeFileSync(this.pathToJson, JSON.stringify(this, null, 2));
Object.assign(this,
JSON.parse(fs.readFileSync(this.pathToJson).toString()),
);
}
}
/**
* JsonFileManager class provides methods to read and update JSON files.
*/
class JsonFileManager {
constructor(pathToJson) {
this.pathToJson = pathToJson;
Object.assign(this, require(this.pathToJson));
}
/**
* Returns a new object excluding the keys specified in the reference array.
* @param {Object} raw - The raw object to filter.
* @param {Array} reference - The array of keys to exclude.
* @returns {Object} - The new object with the specified keys excluded.
*/
excludeKeys(raw, reference) {
return Object.keys(raw).
filter((key) => !reference.includes(key)).
reduce((obj, key) => {
obj[key] = raw[key];
return obj;
}, {});
}
/**
* Saves the current JsonFileManager instance values to the JSON file.
*/
save() {
let classAsJson = JSON.parse(JSON.stringify(this));
let jsonToSave = this.json;
Object.entries(classAsJson).forEach((entry) => {
const key = entry[0].toString();
const value = entry[1];
if (jsonToSave.hasOwnProperty(key)) {
jsonToSave[key] = value;
}
try {
this.fileStream = fs.createWriteStream(this.pathToFile,
{ flags: 'w' });
} catch (error) {
throw error;
}
this.fileStream.write(JSON.stringify(jsonToSave, null, 2) + '\n');
if (this.verbose) console.log(`File saved: ${this.pathToFile}.`);
});
}
}
/**
* Copies an archive file and extracts its contents to the specified
* destination.
* @param {string} source - The path to the source archive file.
* @param {string} destination - The path to the destination where the file
* should be copied and extracted.
* @returns {Promise} - A promise that resolves when the file is copied and
* extracted successfully, or rejects with an error message.
*/
function CopyArchiveAndUnzipSync(source, destination) {
return new Promise((resolve, reject) => {
try {
fs.copyFileSync(source, destination);
fs.createReadStream(source)
.pipe(unZipper.Extract({ path: path.dirname(destination) }))
.on('close', () => {
fs.unlinkSync(destination);
resolve();
});
} catch (error) {
reject('Source file not found!');
}
});
}
/**
* FileManager class provides methods for file and folder operations,
* such as resolving folder paths, creating file paths, deleting files, and
* saving JSON data.
*/
class FileManager {
constructor() {
this.configuration = require('config.json');
this.allFolders = this.configuration.paths;
}
/**
* Returns the current timestamp as a string.
*/
get currentTime() {
return new Date().getTime().toString();
}
/**
* Resolves the absolute folder path based on the provided target folder.
* @param {string} target - The target folder to resolve.
* @returns {string} - The resolved folder path.
*/
resolveFolderPath(target) {
return path.resolve(__dirname, '../../', this.allFolders[target]);
}
/**
* Creates a file path within the specified folder, using the provided
* extension.
* @param {string} folder - The target folder where the file should be
* created.
* @param {string} extension - The file extension.
* @returns {string} - The created file path.
*/
createFilePath(folder, extension) {
return path.resolve(
this.resolveFolderPath(folder), this.currentTime + extension,
);
}
/**
* Deletes files specified in the filesArray.
* @param {Array} filesArray - The array of files to delete.
*/
deleteFiles(filesArray) {
for (const file of filesArray) {
try {
fs.unlinkSync(file.toString());
} catch (error) {
logger.log(error);
}
}
}
/**
* Saves JSON data to a file in the specified folder.
* @param {string} folder - The target folder where the JSON file should be
* saved.
* @param {Object} dataToWrite - The JSON data to write to the file.
* @param {string|null} [filename=null] - The optional filename for the
* JSON file.
*/
saveJson(folder, dataToWrite, filename = null) {
let pathToJson;
if (filename === null)
pathToJson = this.createFilePath(folder, '.json');
else
pathToJson = path.resolve(this.resolveFolderPath(folder), filename);
fs.writeFileSync(pathToJson, JSON.stringify(dataToWrite, null, 2));
}
}
module.exports = {
Configuration,
JsonFileManager,
CopyArchiveAndUnzipSync,
FileManager
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment