1

I have a node application that emits HTML files. This is the jest of how it works:

const fs = require('fs');
const outputPath = './dist/html/';

// code that generates names and content

const currentFile = `${outputPath}${name}.html`;
const content = '...';
fs.promises.writeFile(currentFile, content, 'utf8');

This works as intended, but generally it is a bad practice to write relative path this way (this works on Mac but probably would not work on Windows machine).

const fs = require('fs');
const path = require('path');
const outputPath = path.join(__dirname, 'dist', 'html');

// code that generates names and content

const currentFile = path.join(outputPath, `${name}.html`);
const content = '...';
fs.promises.writeFile(currentFile, content, 'utf8');

This works, but it creates an entire path (User/my.name/Documents/projects/my-project/dist/html/my-file.html) within my project, since fs.writeFile writes the file relative to the working directory.

Can I make fs write file to the absolute path? Alternatively, what is the proper way of generating relative paths?

I ended up using

const outputPath = `.${path.delimiter}dist${path.delimiter}ads${path.delimiter}`;

But this does not seem like the best possible solution.

David Vodrážka
  • 63
  • 1
  • 1
  • 9
  • 1
    You can simply just write the entire absolute path. If you begin a path with a slash, it should be absolute. For example, if I put `fs.promises.WriteFile("/stuff/index.html", "Hello, World!");`, then, on my Windows machine, it would put "C:/stuff/index.html" – Daniel Reynolds Jun 05 '20 at 13:34
  • 1
    I didn't know putting `/` in front of a path makes it absolute. Thank you, it works now as intended :) – David Vodrážka Jun 05 '20 at 13:48
  • Great! I'm glad I could help. :3 – Daniel Reynolds Jun 05 '20 at 13:52

1 Answers1

4

according to the docs, 'fs' module works with both relative and absolute paths.

i guess you issue was somehow related to path building.

here is the working code:

const { promises: fsp } = require('fs');
const { join } = require('path');

const fileName = 'file.html';
const content = '...';

(async () => {
  try {
    await fsp.writeFile(join(process.cwd(), 'dist', 'html', fileName), content);
  } catch (error) { 
    // handling
  }
})();
Yone
  • 867
  • 1
  • 7
  • 22
  • This works, thanks! Is there any difference in using `process.cwd()` and `__dirname`? – David Vodrážka Jun 08 '20 at 06:55
  • 1
    i've user `process.cwd()` because of running code as a single script in node env, where `__dirname` is not defined. here is a complete answer about it - https://stackoverflow.com/a/45145514/7490580 – Yone Jun 08 '20 at 11:01