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'))