Skip to content

Instantly share code, notes, and snippets.

@emersonbroga
Created September 25, 2018 02:36
Show Gist options
  • Save emersonbroga/82f100670a0bb52ae39ab7d960a43c2f to your computer and use it in GitHub Desktop.
Save emersonbroga/82f100670a0bb52ae39ab7d960a43c2f to your computer and use it in GitHub Desktop.
Simple JS Logger that logs to a TXT file.
const fs = require('fs');
const path = require('path');
const DEFAULT_PATH = './output/log.txt';
const getAbsolutePath = (filePath) => {
const absolutePath = path.resolve(filePath);
const fileExists = fs.existsSync(absolutePath);
if (!fileExists) {
throw new Error(`File doesn't exist: ${absolutePath}`);
}
return absolutePath;
}
const getMessage = (data) => {
if (!data) return '';
const isString = (typeof data === 'string');
const text = (isString) ? data : JSON.stringify(data, null, 2);
const message = `\n${text}`;
return message;
};
const log = (data, filePath) => {
try {
const path = getAbsolutePath(filePath || DEFAULT_PATH);
const message = getMessage(data);
fs.appendFileSync(path, message);
} catch (e) {
console.error(e);
}
};
export default log;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment