Angular Icon Get 73% off the Angular Master bundle

See the bundle then add to cart and your discount is applied.

0 days
00 hours
00 mins
00 secs

Write JavaScript like a pro. Javascript Icon

Follow the ultimate JavaScript roadmap.

Relative fs.readFileSync paths with Node.js

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 process.cwd().

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'));

🙌 If you want to learn even more, I’ve built a bunch of TypeScript Courses which might just help you level up your TypeScript skills even further. You should also subscribe to our Newsletter!

Happy coding, and thanks for reading!

Learn JavaScript the right way.

The most complete guide to learning JavaScript ever built.
Trusted by 82,951 students.

Todd Motto

with Todd Motto

Google Developer Expert icon Google Developer Expert

Related blogs 🚀

Free eBooks:

Angular Directives In-Depth eBook Cover

JavaScript Array Methods eBook Cover

NestJS Build a RESTful CRUD API eBook Cover