Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error: ENOENT: no such file or directory NodeJS

I’m trying to build a simple cli app, but I’m getting file not found. The app runs well if I run it in the same directory as the file.

after installing the app globally, it can’t find the file.npm i -g .

$ tran

 Hello World CLI

But if switch directories, I get file not found

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error: ENOENT: no such file or directory, open './hello

bin/index.js

#! /usr/bin/env node

import { hello } from '../index.js';

console.log(hello());

index.js

import fs from 'fs';

export function hello() {
  return fs.readFileSync('./hello', 'utf8');
}

package.json

"bin": {
  "tran": "./bin/index.js"
},
"type": "module",

Also tried using path

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

export function hello() {
  return fs.readFileSync(path.resolve(path.dirname(''),'./hello'), 'utf8');
}

>Solution :

fs.readFileSync resolves relative paths basing on the current process directory (i.e. process.cwd()). To access a file in the same directory as the current module (the module that contains the import) you can create URL based on the current URL plus a relative part in the form

new URL(relativePath, import.meta.url)

So, in the case of your index.js:

import fs from 'fs';

export function hello() {
  return fs.readFileSync(new URL('hello', import.meta.url), 'utf8');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading