在node程序中,如果在使用fs模块读取文件时使用了相对路径,那么在使用CodeRunner运行时无法查找到对应文件,导致报错。
这是因为CodeRunner是以插件本身所在的路径为基准查找文件,而不是以当前工作目录为基准查找。
const fs = require('fs')
// 1 同步读取
const txt_sync = fs.readFileSync('./abc.txt')
console.log(txt_sync)
报错信息为:
Error: ENOENT: no such file or directory, open './abc.txt'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at Object.<anonymous> (f\01_文件读取api.js:5:21)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47 {
errno: -4058,
syscall: 'open',
code: 'ENOENT',
path: './abc.txt'
}
解决方法为修改CodeRunner的配置文件:
"code-runner.executorMap": {
"javascript": "node"
},
修改为:
"code-runner.executorMap": {
"javascript": "cd $dir && node $fileName",
},
完美解决