简体   繁体   English

错误:ENOENT:没有这样的文件或目录 NodeJS

[英]Error: ENOENT: no such file or directory NodeJS

I'm trying to build a simple cli app, but I'm getting file not found.我正在尝试构建一个简单的 cli 应用程序,但找不到文件。 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 bin/index.js

#! /usr/bin/env node

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

console.log(hello());

index.js index.js

import fs from 'fs';

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

package.json package.json

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

Also tried using path也尝试使用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() ). fs.readFileSync根据当前进程目录(即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要访问与当前模块(包含import的模块)位于同一目录中的文件,您可以基于当前 URL 加上表格中的相关部分创建 URL

new URL(relativePath, import.meta.url)

So, in the case of your index.js:因此,对于您的 index.js:

import fs from 'fs';

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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