Skip to content

Instantly share code, notes, and snippets.

@DaveyJake
Created April 11, 2023 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaveyJake/464a01a94a123b8b7b1412df9bb7e4d1 to your computer and use it in GitHub Desktop.
Save DaveyJake/464a01a94a123b8b7b1412df9bb7e4d1 to your computer and use it in GitHub Desktop.
Utility functions for working with files.
/**
* This file contains utility functions for working with your project files.
*
* @link https://nodejs.dev/en/learn/nodejs-file-paths/
*
* @author Davey Jacobson <daveyjake21 [at] geemail [dot] com>
* @version 1.0.0
*/
import fs from 'fs';
/**
* Check if a file exists in the OneRack filesystem.
*
* @since 1.0.0
*
* @param filename Full path with extension for files or no trailing
* slash if checking for a directory.
*
* @returns TRUE if found. FALSE if not.
*/
function fileExists( filename: string ): boolean {
const stats = fs.statSync( filename );
if ( stats.isFile() || stats.isDirectory() ) {
return true;
}
return false;
}
/**
* Get files from directory.
*
* @since 1.0.0
*
* @param directory Full path to directory containing files we need.
*
* @returns Array of filenames with extension if successful. Original
* `directory` argument if not.
*/
function getFiles( directory: string ): Array<string> | string {
const stats = fs.statSync( directory );
if ( ! stats.isDirectory() ) {
console.warn( `${ directory } is a directory!` );
return directory;
}
return fs.readdirSync( directory, { withFileTypes: true }).filter( item => ! item.isDirectory() ).map( item => item.name );
}
/**
* Get file content.
*
* @since 1.0.0
*
* @see fileExists()
*
* @param fileName Full path to file to get contents from.
*
* @returns Stringified data if successful. FALSE if not.
*/
function getFileContent( fileName: string ): string | boolean {
// If file doesn't exists, return false.
if ( ! fileExists( fileName ) ) {
return false;
}
const final = { content: '' };
fs.readFile( filename, 'utf8', ( err, data ) => {
if ( err ) {
console.error( err );
return false;
}
final.content = data.toString();
});
return final.content;
}
export { fileExists, getFiles, getFileContent }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment