Error: ENOENT: no such file or directory NodeJS
Error: ENOENT: no such file or directory NodeJS
我正在尝试构建一个简单的 cli 应用程序,但找不到文件。如果我 运行 将应用程序 运行 与文件放在同一目录中,则该应用程序 运行 运行良好。
全局安装后找不到文件npm i -g .
$ tran
Hello World CLI
但是如果切换目录,我会找不到文件
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",
也尝试使用 path
import fs from 'fs';
import path from 'path';
export function hello() {
return fs.readFileSync(path.resolve(path.dirname(''),'./hello'), 'utf8');
}
fs.readFileSync
根据当前进程目录解析相对路径(即 process.cwd()
)。要访问与当前模块(包含 import
的模块)相同目录中的文件,您可以根据当前 URL 加上表单中的相关部分创建 URL
new URL(relativePath, import.meta.url)
因此,对于您的 index.js:
import fs from 'fs';
export function hello() {
return fs.readFileSync(new URL('hello', import.meta.url), 'utf8');
}
我正在尝试构建一个简单的 cli 应用程序,但找不到文件。如果我 运行 将应用程序 运行 与文件放在同一目录中,则该应用程序 运行 运行良好。
全局安装后找不到文件npm i -g .
$ tran
Hello World CLI
但是如果切换目录,我会找不到文件
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",
也尝试使用 path
import fs from 'fs';
import path from 'path';
export function hello() {
return fs.readFileSync(path.resolve(path.dirname(''),'./hello'), 'utf8');
}
fs.readFileSync
根据当前进程目录解析相对路径(即 process.cwd()
)。要访问与当前模块(包含 import
的模块)相同目录中的文件,您可以根据当前 URL 加上表单中的相关部分创建 URL
new URL(relativePath, import.meta.url)
因此,对于您的 index.js:
import fs from 'fs';
export function hello() {
return fs.readFileSync(new URL('hello', import.meta.url), 'utf8');
}