我正在嘗試構建一個簡單的 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());
索引.js
import fs from 'fs';
export function hello() {
return fs.readFileSync('./hello', 'utf8');
}
包.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');
}
uj5u.com熱心網友回復:
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');
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/379014.html
上一篇:“flutterbuildappbundle”命令中的flutter構建錯誤
下一篇:npm錯誤!無效的選項引數
