Created
September 25, 2018 02:36
-
-
Save emersonbroga/82f100670a0bb52ae39ab7d960a43c2f to your computer and use it in GitHub Desktop.
Simple JS Logger that logs to a TXT file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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