In node.js why i'm not getting error while trying to write the non existing file - node.js

In the below code,i'm trying to write the non existing file 'doesnotexist.text' but still i'm getting the result as success.
var fs = require('fs');
fs.writeFile('doesnotexist.text', 'Hello World!', function (err) {
if (err) {
console.log('error is '+err);
return;
}
else{
console.log('success.');
}
});

Because the writeFile function creates the file if it does not exist.
Basically, you can change the behavior of this function by submitting an options object as third parameter, as described in the documentation. For the flags property you can provide any value from the ones described in the documentation for fs.open.
For write, they are:
w - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx - Like w but opens the file in exclusive mode.
w+ - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+ - Like w+ but opens the file in exclusive mode.
The default value for writeFile is w, hence the file is created if it does not exist. As there is no option that provides an error when the file does not exist, you need an additional check whether the file already exists.
For this, check out the fs.exists function (see documentation for details).
Basically, your code should somewhat like this:
var fs = require('fs');
fs.exists('foo.txt', function (exists) {
if (!exists) {
return 'Error, file foo.txt does not exist!';
}
fs.writeFile('foo.txt', ...);
});

Related

Node JS: What's the difference Between open file in write mode and write mode

I know that write mode can write things but what does open() in write mode do?
var fs = require('fs');
fs.open('mynewfile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});
File open with w flag refers to:-
Open file for writing. The file is created (if it does not exist) or
truncated (if it exists).
For more information please refer Link

Update a file only if it exists Node

I want to update a file using NodeJs only if the file exists.
How to do that.
I read the node docs and fs.exists is deprecated.
If I use fs.writeFile directly it will create a new file if one doesn't exist.
How to update a file only if it exists.
Thanks.
use fs.open and fs.write.
fs.open flags you need:
* 'r+' - Open file for reading and writing. An exception occurs if the file does not exist.
From NodeJs 4.x documentation
var fs = require('fs');
fs.access('/path/to/your/file', fs.F_OK, (err) => {
if (!err) {
// File exists, update your file
}
});
fs.F_OK - File is visible to the calling process. This is useful for determining if a file exists, but says nothing about rwx permissions. Default if no mode is specified.
You can also use the flags fs.R_OK | fs.W_OK | fs.X_OK to additionally check the rwx permissions of the calling process.
Try this:
var fs = require('fs');
var myFile = './mono.txt';
try {
if (!fs.accessSync(myFile)) console.log('File does already exist');
}
catch (exc) {
fs.writeFile(myFile);
}

writeFile no such file or directory

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'
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.
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);
}
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.
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;
});
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.
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});
}
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!");
});
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.
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()...
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).

node.js path.rename() throws error despite working correctly

I am renaming files and are getting some weird behavior. It both works and throws an error.
This is the code:
var fs = require('fs');
var file = {
rename: function(from, to){
fs.rename(from, to, function (err) {
if (err) throw err;
console.log("[i] Renamed " + from + " to " + to);
});
}
}
When using it I get this console output:
main.js:1153 [i] Renamed E:\images\oldName.jpg to E:\images\newName.jpg
main.js:1152 Uncaught Error: ENOENT: no such file or directory, rename 'E:\images\oldName.jpg' -> 'E:\images\newName.jpg'
main.js:1152 (anonymous function)
fs.js:73 (anonymous function)
I don't understand what the problem is. The file is renamed anyway.
Also, it doesn't happen if the file is moved to another folder.
Why is this happening and do I have to worry about it?
The function is being called twice. That means the second time it's called the file is no longer there, leading to the 'no such file or directory'. I notice you're using windows which might also be part of the issue. Are you by any chance using fs.watch to call this function? You might be seeing an inherit problem in fs.watch under Windows duplicating events. If so, there's some example code that might help you.

Create an empty file in Node.js?

For now I use
fs.openSync(filepath, 'a')
But it's a little tricky. Is there a 'standard' way to create an empty file in Node.js?
If you want to force the file to be empty then you want to use the 'w' flag instead:
var fd = fs.openSync(filepath, 'w');
That will truncate the file if it exists and create it if it doesn't.
Wrap it in an fs.closeSync call if you don't need the file descriptor it returns.
fs.closeSync(fs.openSync(filepath, 'w'));
Here's the async way, using "wx" so it fails on existing files.
var fs = require("fs");
fs.open(path, "wx", function (err, fd) {
// handle error
fs.close(fd, function (err) {
// handle error
});
});
If you want it to be just like the UNIX touch I would use what you have fs.openSync(filepath, 'a') otherwise the 'w' will overwrite the file if it already exists and 'wx' will fail if it already exists. But you want to update the file's mtime, so use 'a' and append nothing.

Resources