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

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

翻译自: https://flaviocopes.com/how-to-create-empty-file-node/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值