96

I have a file(data.file an image), I would like to save this image. Now an image with the same name could exist before it. I would like to overwrite if so or create it if it does not exist since before. I read that the flag "w" should do this.

Code:

fs.writeFile('/avatar/myFile.png', data.file, {
  flag: "w"
}, function(err) {
  if (err) {
    return console.log(err);
  }
  console.log("The file was saved!");
});

Error:

[Error: ENOENT: no such file or directory, open '/avatar/myFile.png']
errno: -2,
  code: 'ENOENT',
    syscall: 'open',
      path: '/avatar/myFile.png'
KyleMit
  • 30,350
  • 66
  • 462
  • 664
basickarl
  • 37,187
  • 64
  • 214
  • 335

10 Answers10

146

This is probably because you are trying to write to root of file system instead of your app directory '/avatar/myFile.png' -> __dirname + '/avatar/myFile.png' should do the trick, also check if folder exists. node.js won't create parent folder for you.

SergeS
  • 11,533
  • 3
  • 29
  • 35
  • 1
    Knew it was something trivial, ta. – basickarl Jan 15 '16 at 12:44
  • 36
    The issue I was having was the parent directory didn't exist. Thanks for the tip – C. Louis S. Apr 11 '16 at 18:24
  • how to write the file in different machine in node js. I am tried with path instead of url(http://example.com/files/) but its given the same error. Is possible to upload the file in different server? – Vasanth Apr 03 '18 at 12:13
  • To do so you need to use proper package to upload via SFTP / FTP / whatever. Or you need to have other server linked (So it is accessible via file system, on windows it should have disk letters assigned, on linux mounted) – SergeS Apr 04 '18 at 14:08
46

Many of us are getting this error because parent path does not exist. E.g. you have /tmp directory available but there is no folder "foo" and you are writing to /tmp/foo/bar.txt.

To solve this, you can use mkdirp - adapted from How to write file if parent folder doesn't exist?

Option A) Using Callbacks

const mkdirp = require('mkdirp');
const fs = require('fs');
const getDirName = require('path').dirname;

function writeFile(path, contents, cb) {
  mkdirp(getDirName(path), function (err) {
    if (err) return cb(err);

    fs.writeFile(path, contents, cb);
  });
}

Option B) Using Async/Await

Or if you have an environment where you can use async/await:

const mkdirp = require('mkdirp');
const fs = require('fs');

const writeFile = async (path, content) => {
  await mkdirp(path);
  fs.writeFileSync(path, content);
}
Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
  • Question, why await `writeFileSync`? – eestein Feb 27 '19 at 13:12
  • @eestein good point, no need. Updated. But there is no difference in this case while fs.writeFileSync is just converted to the resolved promise which does nothing in this context. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await – Lukas Liesis Feb 28 '19 at 10:32
  • 2
    `mkdirp` has been made redundant by the addition of a `recursive` option for `fs.mkDir`. [Docs](https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback). – Fdebijl Apr 25 '20 at 23:42
20

I solved a similar problem where I was trying to create a file with a name that contained characters that are not allowed. Watch out for that as well because it gives the same error message.

Svetlin Totev
  • 301
  • 2
  • 3
  • Thanks for this! That's exactly why I was getting it. – Troy Gizzi Mar 31 '22 at 18:40
  • This answer should be higher, for visibility purposes. I was in a cross-platform setup and Jenkins was killing my jobs due to this exact thing. The invalid chard on Windows were the issue. Bless you man! – iamdanchiv Jan 26 '23 at 15:00
18

I ran into this error when creating some nested folders asynchronously right before creating the files. The destination folders wouldn't always be created before promises to write the files started. I solved this by using mkdirSync instead of 'mkdir' in order to create the folders synchronously.

try {
    fs.mkdirSync(DestinationFolder, { recursive: true } );
} catch (e) {
    console.log('Cannot create folder ', e);
}
fs.writeFile(path.join(DestinationFolder, fileName), 'File Content Here', (err) => {
    if (err) throw err;
});
Stev
  • 1,088
  • 10
  • 14
9

Actually, the error message for the file names that are not allowed in Linux/ Unix system comes up with the same error which is extremely confusing. Please check the file name if it has any of the reserved characters. These are the reserved /, >, <, |, :, & characters for Linux / Unix system. For a good read follow this link.

Masihur
  • 501
  • 5
  • 8
  • 3
    This resolved my issue on Windows10 as well - Trying to write a file using Date.toIsoString() in the filename contained colons. Replacing the colons fixed the error. – DShultz May 14 '19 at 14:34
7

It tells you that the avatar folder does not exist. Before writing a file into this folder, you need to check that a directory called "avatar" exists and if it doesn't, create it:

   if (!fs.existsSync('/avatar')) {
      fs.mkdirSync('/avatar', { recursive: true});
    }
Eldar B.
  • 1,097
  • 9
  • 22
Abhay Kumar Upadhyay
  • 2,117
  • 1
  • 7
  • 12
2

you can use './' as a prefix for your path.

in your example, you will write:

fs.writeFile('./avatar/myFile.png', data.file, (err) => {
  if (err) {
    return console.log(err);
  }
  console.log("The file was saved!");
});
ofir_aghai
  • 3,017
  • 1
  • 37
  • 43
1

I had this error because I tried to run:

fs.writeFile(file)
fs.unlink(file)
...lots of code... probably not async issue...
fs.writeFile(file)

in the same script. The exception occurred on the second writeFile call. Removing the first two calls solved the problem.

markemus
  • 1,702
  • 15
  • 23
1

In my case, I use async fs.mkdir() and then, without waiting for this task to complete, I tried to create a file fs.writeFile()...

ktretyak
  • 27,251
  • 11
  • 40
  • 63
0

As SergeS mentioned, using / attempts to write in your system root folder, but instead of using __dirname, which points to the path of the file where writeFile is invoked, you can use process.cwd() to point to the project's directory. Example:

writeFile(`${process.cwd()}/pictures/myFile.png`, data, (err) => {...});

If you want to avoid string concatenations/interpolations, you may also use path.join(process.cwd(), 'pictures', 'myFile.png') (more details, including directory creation, in this digitalocean article).

CPHPython
  • 12,379
  • 5
  • 59
  • 71