在macOS上写入Node.js中的〜/ Documents文件夹?

Geo*_*der 3 javascript macos path node.js home-directory

在Node.js中,我试图写入Documents用户的文件夹(在macOS上):

var logger = fs.createWriteStream('~/Documents/somefolderwhichexists/'+title+'.txt');
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误,但我不确定是什么问题.错误说:

未捕获的异常:错误:ENOENT:没有这样的文件或目录

我怎么能在这里使用绝对路径?或者我的错误是什么?

Pau*_*tos 10

~是您的主目录的简写,由Bash shell扩展.您需要使用完全定义的路径或动态获取当前用户名(或主路径).

要获取当前用户的主路径,请执行以下操作:

var home = require("os").homedir();
var logpath = home + '/Documents/somefolderwhichexists/' + title + '.txt';
var logger = fs.createWriteStream(logpath);
Run Code Online (Sandbox Code Playgroud)