10

I am developing a node.js application on Ubuntu and am trying to programmatically create a directory for my application in the user's home directory.

When I execute the following Javascript in Node:

const fs = require("fs");
fs.mkdirSync("~/mynewdir");

I get the following error:

Error: ENOENT: no such file or directory, mkdir '~/mynewdir'
    at Error (native)
    at Object.fs.mkdirSync (fs.js:923:18)
    at repl:1:4
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:73:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:346:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:545:10)

Executing:

fs.mkdirSync("/home/dah/mynewdir");

works just fine however, but I want to use the home directory of whomever is executing the script.

Does anyone have any suggestions?

Edit - this question is not a duplicate. In this case, the issue is not finding the home directory (I already have this), but why the fs module won't use it.

NoobSaibot
  • 204
  • 1
  • 2
  • 10
java-addict301
  • 3,220
  • 2
  • 25
  • 37
  • 2
    Possible duplicate of [Node.js - Find home directory in platform agnostic way](https://stackoverflow.com/questions/9080085/node-js-find-home-directory-in-platform-agnostic-way) – imjared May 22 '17 at 15:43
  • This isn't a duplicate. The issue was not with finding the home directory, but instead why nodejs fs package was not using it as expected. – java-addict301 May 22 '17 at 19:57

1 Answers1

26

You can do it like that:

const homedir = require('os').homedir();
// `homedir()` returns absolute path so we use `join` here
require("fs").mkdir(require('path').join(homedir, 'mynewdir'));
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488