101

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?

4 Answers 4

179

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'));
Sign up to request clarification or add additional context in comments.

3 Comments

fs.writeFileSync('empty.txt', '');
fs.appendFileSync('do_not_override.txt', '');
you may take a look here for more options than w flag nodejs.org/api/fs.html#fs_file_system_flags
11

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
    });
});

2 Comments

why would you want it to fail?
@NickSotiros so the file doesn't get overwritten, some use cases may want that.
11

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.

Comments

2

You can also use writeFileSync API with an empty string:

fs.writeFileSync(filepath,'');

This will overwrite the file if it already exists.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.