【发布时间】:2020-09-24 16:59:02
【问题描述】:
我有一个发出 HTML 文件的节点应用程序。这是它如何工作的笑话:
const fs = require('fs');
const outputPath = './dist/html/';
// code that generates names and content
const currentFile = `${outputPath}${name}.html`;
const content = '...';
fs.promises.writeFile(currentFile, content, 'utf8');
这按预期工作,但通常以这种方式编写相对路径是一种不好的做法(这适用于 Mac,但可能不适用于 Windows 机器)。
const fs = require('fs');
const path = require('path');
const outputPath = path.join(__dirname, 'dist', 'html');
// code that generates names and content
const currentFile = path.join(outputPath, `${name}.html`);
const content = '...';
fs.promises.writeFile(currentFile, content, 'utf8');
这可行,但它会在我的项目中创建一个完整的路径(User/my.name/Documents/projects/my-project/dist/html/my-file.html),因为fs.writeFile 写入文件相对于工作目录。
我可以让fs 将文件写入绝对路径吗?或者,生成相对路径的正确方法是什么?
我最终使用了
const outputPath = `.${path.delimiter}dist${path.delimiter}ads${path.delimiter}`;
但这似乎不是最好的解决方案。
【问题讨论】:
-
你可以只写整个绝对路径。如果您以斜杠开始路径,则它应该是绝对的。例如,如果我输入
fs.promises.WriteFile("/stuff/index.html", "Hello, World!");,那么,在我的 Windows 机器上,它会输入“C:/stuff/index.html” -
我不知道将
/放在路径前面会使其成为绝对路径。谢谢,它现在按预期工作:) -
太棒了!我很高兴能帮上忙。 :3
标签: javascript node.js path fs