简体   繁体   中英

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

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

fs.readFileSync resolves relative paths basing on the current process directory (ie 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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM