2017-05-08 86 views
2

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

var logger = fs.createWriteStream('~/Documents/somefolderwhichexists/'+title+'.txt'); 

这给了我一个错误,但我不知道什么是错的。错误说:

Uncaught Exception: Error: ENOENT: no such file or directory

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

回答

4

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

要获取当前用户主目录,将ty这样的:

var home = require("os").homedir(); 
var logpath = home + '/Documents/somefolderwhichexists/' + title + '.txt'; 
var logger = fs.createWriteStream(logpath); 
+0

完美!非常感谢。 –

+0

@GeorgeWelder我提供了一个更好的选择,以平台不可知的方式获取用户主目录。请尝试此以及当你有机会:) –

相关问题