我有一个发出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}`;
但这似乎不是最好的解决方案。
我有一个发出HTML文件的节点应用程序。这是开玩笑的样子:const fs = require('fs'); const outputPath ='./dist/html/'; //产生名称和内容的代码const ...
根据docs,'fs'模块适用于相对路径和绝对路径。