Create an empty file in Node.js?

后端 未结 4 1971
礼貌的吻别
礼貌的吻别 2020-12-23 23:55

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条回答
  • 2020-12-24 00:35

    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
        });
    });
    
    0 讨论(0)
  • 2020-12-24 00:40

    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.

    0 讨论(0)
  • 2020-12-24 00:41

    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'));
    
    0 讨论(0)
  • 2020-12-24 00:49

    https://github.com/isaacs/node-touch will do the job and like the UNIX tool it emulates, won't overwrite an existing file.

    0 讨论(0)
提交回复
热议问题