Node.js fs.openSync() 方法
fs.openSync() 方法是 fs 模块的内置应用程序编程接口,用于返回表示文件描述符的整数值。
句法:
fs.openSync( path, flags, mode )
参数:此方法接受三个参数,如上所述,如下所述:
- path:它保存文件的路径。它的类型为字符串、 Buffer 或 URL。
- flags:它保存一个字符串或一个数字值。它的默认值为'r'。
- mode:它保存一个字符串或一个整数值,它的默认值是 0o666。
返回值:它返回一个代表文件描述符的数字。
下面的例子说明了 Node.js 中fs.openSync() 方法的使用:
示例 1:
// Node.js program to demonstrate the
// fs.openSync() method
// Including fs module
var fs = require('fs');
// Defining filename
var filename = './myfile';
// Calling openSync method
// with its parameters
var res = fs.openSync(filename, 'r');
// Prints output
console.log(res);
输出:
23
这里,标志“r”表示文件已经创建,它会读取创建的文件。
示例 2:
// Node.js program to demonstrate the
// fs.openSync() method
// Including fs module
var fs = require('fs');
// Defining path
var path = require('path');
// Calling openSync method with
// all its parameters
var fd = fs.openSync(path.join(
process.cwd(), 'input.txt'), 'w', 0o666);
// This will append the content
// of file created above
fs.writeSync(fd, 'GeeksforGeeks');
// Setting timeout
setTimeout(function () {
// Its printed after the file is closed
console.log('closing file now');
// closing file descriptor
fs.closeSync(fd);
}, 10000);
console.log("Program done!");
输出:
Program done!
closing file now
这里,标志“w”表示文件被创建或覆盖。
参考: https://nodejs.org/api/fs.html#fs_fs_opensync_path_flags_mode