Node js路径模块无法解析目录路径



我想创建一个 CLI 来引导我的项目。一切都可以找到,但为了复制我的模板文件,我使用 ncp 将模板目录作为参数。所以我尝试了,

import chalk from 'chalk';
import path from 'path';
import fs from 'fs';
import { promisify } from 'util';
const access = promisify(fs.access);
...
const templateDir = path.resolve(
new URL(import.meta.url).pathname,
'../../templates',
'project_name'
);
try {
await access(templateDir, fs.constants.R_OK);
} catch (err) {
console.error('%s Invalid template name', chalk.red.bold('ERROR'));
process.exit(1);
}
...

我得到了ERROR Invalid template name

然后我试图找出问题所在,

//* after getting ERROR Invalid template name
//* checking file exist or not
fs.stat(templateDir, function (err, stat) {
if (err == null) {
console.log('File exists');
} else if (err.code === 'ENOENT') {
// file does not exist
console.log("file doesn't exit");
} else {
console.log('Some other error: ', err.code);
}
});
file doesn't exit
[Error: ENOENT: no such file or directory, access 'G:G:CLI%20projectcreate-projecttemplatesjavascript'] {
errno: -4058,
code: 'ENOENT',
syscall: 'access',
path: 'G:\G:\CLI%20project\create-project\templates\javascript'
}
ERROR Invalid template name

我希望访问应该是G:CLI%20projectcreate-projecttemplatesjavascript但它没有给出那个。 错在哪里发生? 顺便说一下,我使用 ESM 模块加载器。

好好读一读你的错误。

[Error: ENOENT: no such file or directory, access 'G:G:CLI%20projectcreate-projecttemplatesjavascript'] {
errno: -4058,
code: 'ENOENT',
syscall: 'access',
path: 'G:\G:\CLI%20project\create-project\templates\javascript'
}

他们不是想欺骗你。他们只是告诉你/

G:\G:\

错误消息的存在是有原因的。

我遇到了同样的问题并找到了答案:

const templateDir = path.resolve(
new URL(import.meta.url).pathname, // This is where it gives the error
'../../templates',
options.template
);

将新的 URL(import.meta.url).pathname更改为__filename。它对我有用。

最新更新