我有一个发出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”模块同时使用相对路径和绝对路径。
我猜你的问题与路径构建有关。
下面是工作代码:
const { promises: fsp } = require('fs');
const { join } = require('path');
const fileName = 'file.html';
const content = '...';
(async () => {
try {
await fsp.writeFile(join(process.cwd(), 'dist', 'html', fileName), content);
} catch (error) {
// handling
}
})();