【问题标题】:Node fs.writefile with absolute path具有绝对路径的节点 fs.writefile
【发布时间】: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


【解决方案1】:

根据docs,“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
  }
})();

【讨论】:

  • 这行得通,谢谢!使用process.cwd()__dirname有什么区别吗?
  • 我有用户 process.cwd(),因为在节点环境中将代码作为单个脚本运行,其中未定义 __dirname。这是一个完整的答案 - stackoverflow.com/a/45145514/7490580
猜你喜欢
  • 2014-02-09
  • 2011-07-23
  • 2011-03-19
  • 2017-06-01
  • 2016-08-03
  • 2019-05-27
  • 1970-01-01
  • 2018-12-28
  • 2011-05-24
相关资源
最近更新 更多