fs.ftruncate should do what you are looking for. EDIT: *Note that you need to open the file "w+" for this to work.
Atomic read and write file. How to set an EOF in certain position?
-
11-04-2022 - |
Question
I'm building a nodejs script. The script flow is as follows:
- Open file with r+ flag.
- then read opened file contents (with fs.read) as json.
- Run user callback to allow a user to manipulate the json (file is still opened)
- Write new object into the file.
- Close the file
My problem is that I don't know how to determine the new size of a file without closing it.
So, for example if first we execute this code:
ffs.lockAndManipulateJSON(__dirname + '/var/meta.json', function (json) {
json.test = 'ABC';
json.foo = 'bar';
});
And in some point in the future:
ffs.lockAndManipulateJSON(__dirname + '/var/meta.json', function (json) {
delete json.foo;
});
The contents of a file would be as follows:
{
"test": "ABC"
} "foo": "bar"
}
But i want it to be:
{
"test": "ABC"
}
So, my question is: how to set the new file size with nodejs while the file is still open?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow