写入文件 fs 模块时出现问题,显然路径位于根级别

Problem writing to file fs module, apparently the path is positioned at the root level

我正在练习 typescript,我想使用 fs 模块编写一个文件,但我不知道这是一个菜鸟问题还是我做错了什么但我的项目看起来像这样:

root

-> dir (here are the js result from tsc)

-> src

--> data

---> data.json

--> service

---> service.ts

--> index.ts

-> package.json

-> tsconfig.json

在 service.ts 显然路径是: let filePath = path.join('./','src','data','data.json') // this works

fs.writeFile(filePath, JSON.stringify(data,null,2), 'utf8', (err)=>{ if(err){ return console.log(err);}})

所以我不知道为什么路径位于根级别

如果我尝试“../data/data.json”,我会收到 ENOENT 错误,没有这样的文件或目录

可以吗?

具有相对路径的文件系统操作始终使用当前工作目录 - 此处解释了一个概念:https://en.m.wikipedia.org/wiki/Working_directory

当您 运行 Node.js 时,您会在特定目录中执行此操作。例如,npm start 之类的脚本通常在 repository/project 的根级目录中执行 - 这会导致所有相对路径从那里开始解析。但是请注意,这在生产环境中可能会有所不同 - Docker、PM2、systemd 或任何其他工具都可以在不同的工作目录中 运行 您的脚本(这通常是配置)。

要检查您在 Node.js 中的当前工作目录,请使用 https://nodejs.org/api/process.html#processcwd

也可以建立相对于JS文件所在目录的路径。本教程展示了有关如何执行此操作的各种示例:https://www.digitalocean.com/community/tutorials/nodejs-how-to-use__dirname

重要的是要记住 require() 使用相对于 __dirname 的路径,但 fs 相对于 CWD 解析。