Never Hardcode Path of files !!!

Never Hardcode Path of files !!!

Often in nodeJS we hardcode paths of files like images , log files, text files or even other js files. This is really a big blunder when yo want your code robust to work in every platform the following problems arises.


The Problem with different path separator

Different operating systems use different path separators:

→ Windows uses backslashes (\), e.g., C:\Users\Project\file.txt.

→ Unix-like systems (macOS, Linux) use forward slashes (/), e.g., /home/user/project/file.txt.

Hardcoding paths with one separator will break your code on other platforms.

Example:

javascript

Copy

// Hardcoded path (Windows-specific)
const filePath = 'C:\\Users\\Project\\file.txt';

This will fail on macOS or Linux because they don’t recognize \ as a path separator.

Also makes code fragile and makes it les maintainable , scalable and flexible.


Then what to Do ?

  1. Hardcoding Paths: Breaks cross-platform compatibility. Fix: Use path.join().

  2. Wrong Separators: Using \ or / manually. Fix: Let path handle separators.

  3. Assuming Directory Structure: Fragile if structure changes. Fix: Use relative paths.

  4. Ignoring Environments: Fails in dev/prod. Fix: Use environment variables.


Always use path module and dynamic paths for robustness.

for example , this is the file structure of a project

my-app/
├── src/
│   └── index.mjs       <-- Your main file
├── log/
│   └── server.log      <-- Log file
└── package.json

Step-by-Step Instructions to read server.log in index.mjs

Step 1: Import Required Modules

In index.mjs, import the path module and fileURLToPath from the url module (to handle __dirname in ES modules).

import path from 'path';
import { fileURLToPath } from 'url';

Step 2: Get the Directory Name of the Current File

Since ES modules don’t have __dirname, use fileURLToPath and path.dirname to get the directory of index.mjs.

const __filename = fileURLToPath(import.meta.url); // Get the file path of index.mjs
const __dirname = path.dirname(__filename);       // Get the directory of index.mjs

Step 3: Construct the Path to server.log

Use path.join() to create a platform-independent path to the server.log file in the log folder.

const logFilePath = path.join(__dirname, '../log/server.log'); // Go up one level and into the log folder

Step 4: Use the Path

Now you can use logFilePath to read, write, or append to the server.log file. For example, to read the file:

import fs from 'fs';

fs.readFile(logFilePath, 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading log file:', err);
    return;
  }
  console.log('Log file content:', data);
});

Hope it helps !!!