In this post you’ll learn how to use fs.readFileSync to give you a relative path to your asset.
By default, that’s not the case and Node.js looks at the root of the project directory - so we’re here to change that.
🕵️♂️ File System String path docs: String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as determined by calling
I was recently coding a Node.js API and needed to access an image to add into a PDF. This meant using
fs (filesystem) from Node.js like so:
import fs from 'fs'; const logo = fs.readFileSync('./assets/img/logo.svg');
This worked just fine, when the
assets/ folder was in the root of my project. But I moved it into a sub-folder, which then meant everything blew up.
Turns out, you need to use path.resolve alongside
__dirname to make it relative:
import fs from 'fs'; import path from 'path'; const logo = fs.readFileSync(path.resolve(__dirname, './assets/img/logo.svg'));
I like to architect my Node.js apps in TypeScript, so below I’ll add the CommonJS syntax.
✅ If you want to build Node.js apps with TypeScript, check out Node + TypeScript + Express project on GitHub!
So, if you’re using CommonJS imports with
require then you’ll have something like this instead:
const fs = require('fs'); const path = require('path'); const logo = fs.readFileSync(path.resolve(__dirname, './assets/img/logo.svg'));
Happy coding, and thanks for reading!