fs.openSync()方法是fs模块的内置应用程序编程接口,用于返回代表文件描述符的整数值。
用法:
fs.openSync( path, flags, mode )
参数:此方法接受上述和以下所述的三个参数:
- path:它保存文件的路径。它的类型为字符串,缓冲区或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
相关用法
- Node.js GM quality()用法及代码示例
- Node.js GM resize()用法及代码示例
- Node.js GM chop()用法及代码示例
- Node.js GM drawPolyline()用法及代码示例
- Node.js GM raise()用法及代码示例
- Node.js GM paint()用法及代码示例
- Node.js GM flop()用法及代码示例
- Node.js GM segment()用法及代码示例
- Node.js GM drawArc()用法及代码示例
注:本文由纯净天空筛选整理自nidhi1352singh大神的英文原创作品 Node.js | fs.openSync() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。