Skip to content

Instantly share code, notes, and snippets.

@tripulse
Last active September 20, 2020 08:53
Show Gist options
  • Select an option

  • Save tripulse/fd18c880deea44b53f1b2ed1aa66a07d to your computer and use it in GitHub Desktop.

Select an option

Save tripulse/fd18c880deea44b53f1b2ed1aa66a07d to your computer and use it in GitHub Desktop.
Short robust library overlies on fs module.
const fs = require("fs");
const path = require("path");
let file = {
pipes: [],
/**
* Adds new file into pipes as objects which could be later acessed.
* @param {String} file - Filename to read a specific file.
* @param {String | Number} mode - Options that how the Interpreter will load the file.
*/
add: function(file, mode) {
if(fs.existsSync(file)) {
var fileSize = fs.statSync(file).size, /* Getting filesize */
fileBuffer = new Buffer.alloc(fileSize), /* Intializing buffer */
fd = fs.openSync(path.resolve(file), mode, 0o666); /* Opening file Syncroniously */
fs.readSync(fd, fileBuffer, 0, fileSize, null); /* Reading file data and storing to a buffer. */
var fileObject = {
descriptor: fd,
buffer: fileBuffer,
length: fileSize
}; /* Pushing data to array which could be later acessed. */
this.pipes.push(fileObject);
return fileObject;
}
},
/**
* Returns file Object using a file descriptor.
* @param {Number} fd - File Descriptor (aka. File pipe index)
*/
get: function(fd) {
if(isNaN(fd)) throw new Error("File descriptor should be a number");
else if(!isInt(fd)) throw new Error("File descriptor should be integer");
else {
this.pipes.find((element) => {
if(element.descriptor == fd) return element; /* If the descriptor stored in array matches with argument. */
else throw new Error("Descriptor isn't even opened");
});
}
},
/**
* Removes file Object using a file descriptor.
* @param {Number} fd - File Descriptor (aka. File pipe index)
*/
remove: function(fd) {
if(isNaN(fd)) throw new Error("File descriptor should be a number");
else if(!isInt(fd)) throw new Error("File descriptor should be integer");
else {
this.pipes.find((element, index) => {
if(element.descriptor == fd) this.pipes.splice(index, 1); /* If descriptor matches stored in array with argument. */
else throw new Error("Descriptor isn't even opened");
});
}
}
};
/**
* Checks whether number is integer or not.
* @param {Number} number - The value itself to check whether it's integer or not.
*/
function isInt(number) {
if(Math.trunc(number) < number) false;
else true;
}
module.exports = file; /* Exporting the entire library. */
@tripulse
Copy link
Copy Markdown
Author

What's the point of this library?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment