Question

I'm building a nodejs script. The script flow is as follows:

  1. Open file with r+ flag.
  2. then read opened file contents (with fs.read) as json.
  3. Run user callback to allow a user to manipulate the json (file is still opened)
  4. Write new object into the file.
  5. 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?

Was it helpful?

Solution

fs.ftruncate should do what you are looking for. EDIT: *Note that you need to open the file "w+" for this to work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top