Stefan Stefan - 7 months ago 35
Javascript Question

node.js open file overrides existing file

i am creating a file in a c like so:

int fd;
fd = open(filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

if (fd == -1) {
return NULL;
}

lseek(fd, filesize + 1, SEEK_SET);

write(fd, "", 1);

lseek(fd, 0, SEEK_SET);

void* file_memory = mmap(0, filesize, PROT_WRITE, MAP_SHARED, fd, 0);

close(fd);


So, as I said, I create the file and fill it before mapping it in memory.

When i look at the file in the filesystem it gives me 1026 bytes of filesize (simple ls -l from the file)

Later I want to access the file from a node application simple and sound like so:

fs.open(filename, 'w', function (err, fd) { ... }


When this line is executed the filesize is then set to 0 (again a simple ls -l).

I assume that the file has been recreated? But that should not happen since the file already exists (according to the node.js manual).

What is happening here? What am I doing wrong?

Answer

When I use the 'w+' flag, it works.

Don't know why because the 'w+' means that it can read and write the file while the 'w' means that it only can write the file.

fs.open(filename, 'w', function (err, fd) { ... }

EDIT

From man fopen

w

Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.

w+

Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.