4

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?

Paulo Mattos
  • 16,310
  • 10
  • 64
  • 73
George Welder
  • 2,950
  • 7
  • 31
  • 62

1 Answers1

13

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);
Paulo Mattos
  • 16,310
  • 10
  • 64
  • 73
  • @GeorgeWelder I provided a better alternative, getting the user home directory in platform agnostic way. Please try this as well when you get a chance :) – Paulo Mattos May 08 '17 at 23:47