Node JS: What's the difference Between open file in write mode and write mode - node.js

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

Related

How to read the contents of a file onto the console using Nodejs

I am going back to learning js after many years off and all i want to do is read the contents of a file onto the console using Nodejs. I found the sample code. Nice and simple. I have spent over an hour trying to figure out why it will not find the file. This is sample right off the documentation and i made it exactly like the example to debug it. The absolute only difference is the name joe is replaced with my user folder.
const fs = require('fs')
fs.readFile('/Users/gendi/test.txt', 'utf8' , (err, data) => {
if (err) {
console.error(err)
return
}
console.log(data)
})
It runs fine except it will not find test.text. no matter what. I receive the following error and no matter how i format the file path. Nothing.
C:\Users\gendi>node readfile.js
[Error: ENOENT: no such file or directory, open 'C:\Users\gendi\test.txt'] {
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\Users\\gendi\\pcsSnipe\\test.txt'
}
You can also only pass in the file path as 'test.txt' and the exact same results come up. on the first part of the error msg the path looks formatted correctly but on the last line of the error msg it is not? Its been years.. so i know i am missing something really simple. I assure that file is there!! Thank you in advance and forgive my ineptness.
The fs module requires an exact path to the file you'd like to read. A simple fix to this would be to add __dirname which will return the directory path along with the path of your file.
// Define modules
const fs = require('fs');
const path = require('path');
// Read the file
fs.readFile(path.join(__dirname, '/Users/gendi/test.txt'), 'utf8' , (err, data) => {
if (err) // If FS returned an error
return console.error(err); // Log the error and return
console.log(data); // If the reading was successful, log the data
});
It works if you remove the file extention, '.txt' . Idk why it make a differnce. maybe the "." is throwing it off but it doesn't matter in this respect. Thank you

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).

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

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', ...);
});

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