Node.js: filename with trailing slash


TL;DR: replace / with \u2215.

Problem

In Node.js, when writing to a filename with a trailing slash (/), it gets evaluated as a directory path.

Example

Writing to the filename try/catch.txt:

const filename = 'try/catch.txt';
require('fs').writeFileSync(filename);

Throws the error:

Error: ENOENT: no such file or directory, open 'try/catch.txt'

Solution

To write to a filename with a trailing slash, replace the / with the Unicode equivalent \u2215:

const filename = 'try/catch.txt'.replace('/', '\u2215');
require('fs').writeFileSync(filename);

To replace all trailing slashes with the Unicode equivalent:

const filename = 'try/catch/finally.txt'.replace(/\//g, '\u2215');
require('fs').writeFileSync(filename);

Demo

Repl.it:



Please support this site and join our Discord!