Skip to content

Instantly share code, notes, and snippets.

@GalassoLuca
Last active May 5, 2022 14:04
Show Gist options
  • Save GalassoLuca/5f0bd792b02ab5e3683cbc982913dba3 to your computer and use it in GitHub Desktop.
Save GalassoLuca/5f0bd792b02ab5e3683cbc982913dba3 to your computer and use it in GitHub Desktop.
How to read a file in NodeJS from a relative path
const fs = require('fs')
const path = require('path')
const html1 = fs.readFileSync(path.join(__dirname, '../test/fixtures/page1.html'), 'utf-8')
// in one line
const html2 = require('fs').readFileSync(require('path').join(__dirname, '../test/fixtures/page2.html'), 'utf-8')
// with a function
const readFile = relativePath => require('fs').readFileSync(require('path').join(__dirname, relativePath), 'utf-8')
const html3 = readFile('../test/fixtures/page3.html')
const html4 = readFile('../test/fixtures/page4.html')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment