Home > OS >  Error: ENOENT: no such file or directory NodeJS
Error: ENOENT: no such file or directory NodeJS

Time:12-08

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

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

CodePudding user response:

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');
}
  • Related