DEV Community

Smart Home Dan
Smart Home Dan

Posted on

NodeJS Basics: File System Usage

Accessing files from the OS in Node needs to be done in a certain way.

When doing the import method, I found we were actually only loading the code at load time, and the files were being manpulated during runtime.

import payload from './payload.json';
Enter fullscreen mode Exit fullscreen mode

This method didn't work when supplying data for API's.

The solution was to load in the files using the Node FileSystem module.

The snippet below shows how to do it.

import fs from 'fs';
import path from 'path';

const filepath = path.join(__dirname, 'payload.json');

const filePayloadRaw = fs.readFileSync(filepath, 'utf8');

const filePayload = JSON.parse(filePayloadRaw);
Enter fullscreen mode Exit fullscreen mode

Few Notes on the above.

  • __dirname is an inbuilt variable to essentially give you the current directory location. This is important as when you run the node using Typescript, you will be in a src/ directory, so when you build it, the file location is wrong because you are executing from the /dist directory. __dirname gives you the runtime location.

  • fs.readFileSync() needs to be passed in a character encoding. Additionally fs also provides a readFile() function which is async.

  • The raw result from fs is not usable until you parse it with the JSON library.

Top comments (0)