The method fs.openSync() provided by the fs built-in module is the best way.
内置模块fs提供的方法fs.openSync()是最好的方法。
It returns a file descriptor:
它返回一个文件描述符:
const fs = require('fs')
const filePath = './.data/initialized'
const fd = fs.openSync(filePath, 'w')
the w flag makes sure the file is created if not existing, and if the file exists it overwrites it with a new file, overriding its content.
w标志可确保文件(如果不存在)已创建,如果文件存在,则它将用新文件覆盖该文件,从而覆盖其内容。
Use the a flag to avoid overwriting. The file is still created if not existing.
使用a标志,以避免覆盖。 如果不存在,仍会创建该文件。
If you don’t need the file descriptor, you can wrap the call in a fs.closeSync() call, to close the file:
如果不需要文件描述符,可以将调用包装在fs.closeSync()调用中以关闭文件:
const fs = require('fs')
const filePath = './.data/initialized'
fs.closeSync(fs.openSync(filePath, 'w'))
本文介绍在Node.js中使用fs内置模块的fs.openSync()方法创建空文件的最佳实践。此方法通过指定w或a标志来控制文件的创建与写入行为,确保文件创建或避免覆盖现有文件。

400

被折叠的 条评论
为什么被折叠?



