sync.js (1604B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2019 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var open = require( 'fs' ).openSync; // eslint-disable-line no-sync, stdlib/no-redeclare 24 var defaults = require( './defaults.json' ); 25 26 27 // MAIN // 28 29 /** 30 * Synchronously opens a file. 31 * 32 * @param {(string|Buffer)} path - file path 33 * @param {(string|number)} [flags='r'] - file system flags 34 * @param {integer} [mode=0o666] - file mode 35 * @returns {(integer|Error)} file descriptor or an error 36 * 37 * @example 38 * var closeSync = require( '@stdlib/fs/close' ).sync; 39 * 40 * var fd = openSync( __filename ); 41 * if ( fd instanceof Error ) { 42 * throw fd; 43 * } 44 * closeSync( fd ); 45 */ 46 function openSync( path, flags, mode ) { 47 var nargs; 48 var fd; 49 50 nargs = arguments.length; 51 try { 52 if ( nargs === 1 ) { 53 fd = open( path, defaults.flags, defaults.mode ); 54 } else if ( nargs === 2 ) { 55 fd = open( path, flags, defaults.mode ); 56 } else { 57 fd = open( path, flags, mode ); 58 } 59 } catch ( err ) { 60 return err; 61 } 62 return fd; 63 } 64 65 66 // EXPORTS // 67 68 module.exports = openSync;