在 Node.js 中创建一个空文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12809068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:27:21  来源:igfitidea点击:

Create an empty file in Node.js?

node.jsfilesystems

提问by Lai Yu-Hsuan

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?

但这有点棘手。有没有一种“标准”的方式在 Node.js 中创建一个空文件?

回答by JohnnyHK

If you want to force the file to be empty then you want to use the 'w'flag instead:

如果要强制文件为空,则要改用该'w'标志:

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.closeSynccall if you don't need the file descriptor it returns.

fs.closeSync如果您不需要它返回的文件描述符,请将其包装在调用中。

fs.closeSync(fs.openSync(filepath, 'w'));

回答by Kyle Mathews

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

https://github.com/isaacs/node-touch将完成这项工作,就像它模拟的 UNIX 工具一样,不会覆盖现有文件。

回答by silverwind

Here's the async way, using "wx"so it fails on existing files.

这是异步方式,使用"wx"so 它在现有文件上失败。

var fs = require("fs");
fs.open(path, "wx", function (err, fd) {
    // handle error
    fs.close(fd, function (err) {
        // handle error
    });
});

回答by Nick Sotiros

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.

如果您希望它像 UNIX touch 一样,我会使用您拥有的东西,fs.openSync(filepath, 'a')否则如果文件已经存在,'w' 将覆盖该文件,如果它已经存在,'wx' 将失败。但是您想更新文件的 mtime,所以使用 'a' 并且不附加任何内容。