简体   繁体   中英

Writing to ~/Documents folder in Node.js on macOS?

In Node.js, I am attempting to write into the Documents folder of the user (on macOS):

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

This gives me an error, but I am not sure what is wrong. The error says:

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

How could I use an absolute path here? Or what is my mistake?

The ~ is a shorthand, to your home directory , expanded by the Bash shell. You need to use a fully defined path or get the current user name (or home path) dynamically.

To get the current user home path, ty this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM