Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fs.readFileSync is not file relative? Node.js

Tags:

path

node.js

People also ask

What is the difference between readFile and readFileSync?

readFileSync() is synchronous and blocks execution until finished. These return their results as return values. readFile() are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish.

What is FS readFileSync?

readFileSync() method is an inbuilt application programming interface of fs module which is used to read the file and return its content. In fs. readFile() method, we can read a file in a non-blocking asynchronous way, but in fs. readFileSync() method, we can read files in a synchronous way, i.e. we are telling node.

What is __ Dirname in node?

__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.

How do you create an absolute path in node JS?

Use the path. resolve() method to get an absolute path of a file from a relative path in Node. js, e.g. path. resolve('./some-file.


You can resolve the path relative the location of the source file - rather than the current directory - using path.resolve:

const path = require("path");
const file = fs.readFileSync(path.resolve(__dirname, "../file.xml"));

Just to expand on the above, if you are using fs.readFileSync with TypeScript (and of course CommonJS) here's the syntax:

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

const logo = fs.readFileSync(path.resolve(__dirname, './assets/img/logo.svg'));

This is because fs.readFileSync() is resolved relative to the current working directory, see the Node.js File System docs for more info.

Source: Relative fs.readFileSync paths with Node.js

And of course, the CommonJS format:

const fs = require('fs');
const path = require('path');

const logo = fs.readFileSync(path.resolve(__dirname, './assets/img/logo.svg'));