UNPKG

game-battleship

Version:
117 lines (88 loc) 3.38 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Source: fileReader.js</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: fileReader.js</h1> <section> <article> <pre class="prettyprint source linenums"><code>const assert = require("assert"); const readline = require("readline"); const fs = require("fs"); /** * This function would read file from a path line by line and populate the filecontent * object for further processing * @param {string} filePath * @param {Readable} testStream : sole purpose of this stream is for testing * @returns {Promise} this would resolve when all of the content is read from the file */ function fileReader(filePath, testStream) { return new Promise((resolve, reject) => { try { if (!testStream) { assert(filePath, "input file path is empty"); } const fileContent = { "ships": [] }; let lineCount = 0; const lineReader = readline.createInterface({ "input": testStream || fs.createReadStream(filePath) }); lineReader.on("line", function (line) { lineCount++; switch (true) { case (lineCount === 1): fileContent.AreaDimensions = line.trim(); break; case (lineCount === 2): fileContent.shipCount = parseInt(line.trim(), 10); break; case (lineCount > 2 &amp;&amp; lineCount &lt;= (fileContent.shipCount + 2)): fileContent.ships.push(line.trim()); break; case (lineCount === (fileContent.shipCount + 3)): fileContent.player1Targets = line.trim(); break; case (lineCount === (fileContent.shipCount + 4)): fileContent.player2Targets = line.trim(); break; default: break; } }); lineReader.on("close", function () { return resolve(fileContent); }); } catch (error) { console.log("Error reading file, Please check the file path", error); reject(error); } }); } module.exports = fileReader; </code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Home</a></h2><h3>Global</h3><ul><li><a href="global.html#fileReader">fileReader</a></li></ul> </nav> <br class="clear"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Tue Feb 19 2019 00:45:50 GMT+0530 (India Standard Time) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html>