From 824d987a108dd1f8b0566db4a9996734109200f7 Mon Sep 17 00:00:00 2001 From: remi Date: Thu, 13 Jun 2024 22:10:35 -0400 Subject: [PATCH 01/12] FIRST ASSIGNMENT --- .../exercises/data-and-variables-exercises.js | 43 ++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/data-and-variables/exercises/data-and-variables-exercises.js b/data-and-variables/exercises/data-and-variables-exercises.js index 6433bcd641..79d888fd93 100644 --- a/data-and-variables/exercises/data-and-variables-exercises.js +++ b/data-and-variables/exercises/data-and-variables-exercises.js @@ -1,11 +1,52 @@ // Declare and assign the variables below +let spaceShuttleName = "Determination"; + +let shuttleSpeedMph = 17500; + +let distanceToMarsKm = 225000000; + +let distanceMoonKm = 384400; + +let milesPerKilometer = 0.621; + + + + // Use console.log to print the 'typeof' each variable. Print one item per line. +console.log(typeof spaceShuttleName); + +console.log(typeof shuttleSpeedMph); + +console.log(typeof distanceToMarsKm); + +console.log(typeof distanceMoonKm); + +console.log(typeof milesPerKilometer); + + // Calculate a space mission below +let milesToMars = distanceToMarsKm * milesPerKilometer; + +let hoursToMars = milesToMars / shuttleSpeedMph; + +let daysToMars = hoursToMars / 24; + + // Print the results of the space mission calculations below +console.log(spaceShuttleName + " will take " + daysToMars + " to get to Mars."); + // Calculate a trip to the moon below -// Print the results of the trip to the moon below \ No newline at end of file +let milesToMoon = distanceMoonKm * milesPerKilometer; + +let hoursToMoon = milesToMoon / shuttleSpeedMph; + +let daysToMoon = hoursToMoon / 24; + +// Print the results of the trip to the moon below + +console.log(spaceShuttleName + " will take " + daysToMoon + " to get to the Moon."); \ No newline at end of file From c4013793f1d57ac9fb61937e8113127dac063d9f Mon Sep 17 00:00:00 2001 From: remi Date: Mon, 17 Jun 2024 00:11:50 -0400 Subject: [PATCH 02/12] finished assignment CH5 --- booleans-and-conditionals/exercises/part-1.js | 21 ++++++--- booleans-and-conditionals/exercises/part-2.js | 46 +++++++++++++++++-- booleans-and-conditionals/exercises/part-3.js | 31 +++++++++++-- 3 files changed, 84 insertions(+), 14 deletions(-) diff --git a/booleans-and-conditionals/exercises/part-1.js b/booleans-and-conditionals/exercises/part-1.js index b829140a07..4f5cfcb808 100644 --- a/booleans-and-conditionals/exercises/part-1.js +++ b/booleans-and-conditionals/exercises/part-1.js @@ -1,11 +1,20 @@ // Declare and initialize the variables for exercise 1 here: +let engineIndicatorLight = "red blinking" +let spaceSuitsOn = true +let shuttleCabinReady = true +let crewStatus = spaceSuitsOn && shuttleCabinReady +let computerStatusCode = 200 +let shuttleSpeed = 15000 + + + // BEFORE running the code, predict what will be printed to the console by the following statements: if (engineIndicatorLight === "green") { - console.log("engines have started"); -} else if (engineIndicatorLight === "green blinking") { - console.log("engines are preparing to start"); -} else { - console.log("engines are off"); -} + console.log("engines have started"); + } else if (engineIndicatorLight === "green blinking") { + console.log("engines are preparing to start"); + } else { + console.log("engines are off"); + } \ No newline at end of file diff --git a/booleans-and-conditionals/exercises/part-2.js b/booleans-and-conditionals/exercises/part-2.js index ff11fbab8a..e3b147a22b 100644 --- a/booleans-and-conditionals/exercises/part-2.js +++ b/booleans-and-conditionals/exercises/part-2.js @@ -1,4 +1,4 @@ -let engineIndicatorLight = "red blinking"; +let engineIndicatorLight = "red blinking";//THIS IS A STRING NOT A VARIABLE SO "" ARE ADDED let spaceSuitsOn = true; let shuttleCabinReady = true; let crewStatus = spaceSuitsOn && shuttleCabinReady; @@ -9,13 +9,53 @@ let shuttleSpeed = 15000; // a) If crewStatus is true, print "Crew Ready" else print "Crew Not Ready". - +if (crewStatus === true) { + console.log("Crew Ready");// ; IS ON THIS LINE NOT AT THE FIRST LINE +} else { + console.log("Crew Not Ready"); +} +/* +if (crewStatus) { THIS IS ANOTHER WAY OF WRITING THE ABOVE STATEMENT BUT BOTH WAYS ARE CORRECT? + console.log("Crew Ready"); + } else { + console.log("Crew Not Ready"); + } +*/ // b) If computerStatusCode is 200, print "Please stand by. Computer is rebooting." Else if computerStatusCode is 400, print "Success! Computer online." Else print "ALERT: Computer offline!" +if (computerStatusCode === 200) { + console.log("Please stand by. Computer is rebooting"); +} else if (computerStatusCode === 400) { + console.log("Success! Computer online."); +} else { + console.log("ALERT: Computer offline!"); +} + // c) If shuttleSpeed is > 17,500, print "ALERT: Escape velocity reached!" Else if shuttleSpeed is < 8000, print "ALERT: Cannot maintain orbit!" Else print "Stable speed". +if (shuttleSpeed > 17500) { + console.log("ALERT: Escape velocity reached!"); +} else if (shuttleSpeed < 8000) { + console.log("ALERT: Cannot maintain orbit!"); +} else { + console.log("Stable speed"); +} + // 4) PREDICT: Do the code blocks shown in the 'predict.txt' file produce the same result? -console.log(/* "Yes" or "No" */); +/*COMPARE THESE TWO LOOPS TO PREDICT THE OUTCOME! +if (crewStatus && computerStatusCode === 200 && spaceSuitsOn) { + console.log("all systems go"); +} else { + console.log("WARNING. Not ready"); +} +if (!crewStatus || computerStatusCode !== 200 || !spaceSuitsOn) { + console.log("WARNING. Not ready"); +} else { + console.log("all systems go"); +} +*/ + +console.log("No"); diff --git a/booleans-and-conditionals/exercises/part-3.js b/booleans-and-conditionals/exercises/part-3.js index 9ed686d097..b8254bd95c 100644 --- a/booleans-and-conditionals/exercises/part-3.js +++ b/booleans-and-conditionals/exercises/part-3.js @@ -1,24 +1,45 @@ let engineIndicatorLight = 'red blinking'; let fuelLevel = 21000; let engineTemperature = 1200; +let commandOverride = true; + /* 5) Implement the following checks using if/else if/else statements: -a) If fuelLevel is above 20000 AND engineTemperature is at or below 2500, print "Full tank. Engines good." +a) If fuelLevel is above 20000 AND engineTemperature is at or below 2500, print "Full tank. Engines good."! -b) If fuelLevel is above 10000 AND engineTemperature is at or below 2500, print "Fuel level above 50%. Engines good." +b) If fuelLevel is above 10000 AND engineTemperature is at or below 2500, print "Fuel level above 50%. Engines good."! -c) If fuelLevel is above 5000 AND engineTemperature is at or below 2500, print "Fuel level above 25%. Engines good." +c) If fuelLevel is above 5000 AND engineTemperature is at or below 2500, print "Fuel level above 25%. Engines good."! -d) If fuelLevel is at or below 5000 OR engineTemperature is above 2500, print "Check fuel level. Engines running hot." +d) If fuelLevel is at or below 5000 OR engineTemperature is above 2500, print "Check fuel level. Engines running hot."! -e) If fuelLevel is below 1000 OR engineTemperature is above 3500 OR engineIndicatorLight is red blinking print "ENGINE FAILURE IMMINENT!" +e) If fuelLevel is below 1000 OR engineTemperature is above 3500 OR engineIndicatorLight is red blinking print "ENGINE FAILURE IMMINENT!" ! f) Otherwise, print "Fuel and engine status pending..." */ // Code 5a - 5f here: +if (fuelLevel > 20000 && engineTemperature <= 2500) { + console.log("Full tank. Engines good."); +} else if (fuelLevel > 10000 && engineTemperature <= 2500) { + console.log("Fuel level above 50%. Engines good."); +} else if (fuelLevel > 5000 && engineTemperature <= 2500) { + console.log("Fuel leve above 25%. Engines good."); +} else if (fuelLevel <= 5000 || engineTemperature > 2500) { + console.log("Check fuel level. Engines running hot."); +} else if (fuelLevel < 1000 || engineTemperature > 3500 || engineIndicatorLight === 'red blinking') { + console.log("ENGINE FAILURE IMMINENT!"); +} else { + console.log("Fuel and engine status pending..."); +} + // 6) a) Create the variable commandOverride, and set it to be true or false. If commandOverride is false, then the shuttle should only launch if the fuel and engine check are OK. If commandOverride is true, then the shuttle will launch regardless of the fuel and engine status. /* 6) b) Code the following if/else check: If fuelLevel is above 20000 AND engineIndicatorLight is NOT red blinking OR commandOverride is true print "Cleared to launch!" Else print "Launch scrubbed!" */ +if (fuelLevel > 20000 && engineIndicatorLight !== 'red blinking' || commandOverride === true) {// alternatively !engineIndicatorLight could be used + console.log("Cleared to launch!"); +} else { + console.log("Launch scrubbed!") +} \ No newline at end of file From da7c60afd4b28982a686ec93e33b42fbba262822 Mon Sep 17 00:00:00 2001 From: remi Date: Mon, 17 Jun 2024 15:00:17 -0400 Subject: [PATCH 03/12] V2 HW ASSIGNMENT CH5 --- booleans-and-conditionals/exercises/part-2.js | 2 +- booleans-and-conditionals/exercises/part-3.js | 28 ++++++++++++------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/booleans-and-conditionals/exercises/part-2.js b/booleans-and-conditionals/exercises/part-2.js index e3b147a22b..ba32cda0b9 100644 --- a/booleans-and-conditionals/exercises/part-2.js +++ b/booleans-and-conditionals/exercises/part-2.js @@ -25,7 +25,7 @@ if (crewStatus) { THIS IS ANOTHER WAY OF WRITING THE ABOVE STATEMENT BUT BOTH WA if (computerStatusCode === 200) { console.log("Please stand by. Computer is rebooting"); -} else if (computerStatusCode === 400) { +} else if (computerStatusCode === 400) { console.log("Success! Computer online."); } else { console.log("ALERT: Computer offline!"); diff --git a/booleans-and-conditionals/exercises/part-3.js b/booleans-and-conditionals/exercises/part-3.js index b8254bd95c..cb31a03d7f 100644 --- a/booleans-and-conditionals/exercises/part-3.js +++ b/booleans-and-conditionals/exercises/part-3.js @@ -1,3 +1,7 @@ +//V2 +//EDITED UPDATED ELSE IF LINES AND TESTED CODE +//THIS EXPECTED OUTPUT IS TO LAUNCH AND OVERRIDE WARNING SIGNS :D + let engineIndicatorLight = 'red blinking'; let fuelLevel = 21000; let engineTemperature = 1200; @@ -20,17 +24,18 @@ f) Otherwise, print "Fuel and engine status pending..." */ // Code 5a - 5f here: -if (fuelLevel > 20000 && engineTemperature <= 2500) { - console.log("Full tank. Engines good."); -} else if (fuelLevel > 10000 && engineTemperature <= 2500) { - console.log("Fuel level above 50%. Engines good."); -} else if (fuelLevel > 5000 && engineTemperature <= 2500) { - console.log("Fuel leve above 25%. Engines good."); + +if (fuelLevel < 1000 || engineTemperature > 3500 || engineIndicatorLight === 'red blinking') { + console.log("ENGINE FAILURE IMMINENT!"); } else if (fuelLevel <= 5000 || engineTemperature > 2500) { console.log("Check fuel level. Engines running hot."); -} else if (fuelLevel < 1000 || engineTemperature > 3500 || engineIndicatorLight === 'red blinking') { - console.log("ENGINE FAILURE IMMINENT!"); -} else { +} else if (fuelLevel > 5000 && engineTemperature <= 2500) { + console.log("Fuel level above 25%. Engines good."); +} else if (fuelLevel > 10000 && engineTemperature <= 2500) { + console.log("Fuel level above 50%. Engines good."); +} else if (fuelLevel > 20000 && engineTemperature <= 2500) {//REREAD THE CODE TO BE SURE ALL NUMBERS ARE CORRECT + console.log("Full tank. Engines good."); +} else { console.log("Fuel and engine status pending..."); } @@ -38,8 +43,11 @@ if (fuelLevel > 20000 && engineTemperature <= 2500) { /* 6) b) Code the following if/else check: If fuelLevel is above 20000 AND engineIndicatorLight is NOT red blinking OR commandOverride is true print "Cleared to launch!" Else print "Launch scrubbed!" */ + if (fuelLevel > 20000 && engineIndicatorLight !== 'red blinking' || commandOverride === true) {// alternatively !engineIndicatorLight could be used console.log("Cleared to launch!"); } else { console.log("Launch scrubbed!") -} \ No newline at end of file +} + + From 337d2bb2b7d47c899968555e80645d276670a3cb Mon Sep 17 00:00:00 2001 From: remi Date: Mon, 17 Jun 2024 15:07:35 -0400 Subject: [PATCH 04/12] V1 HW CH6 --- .../exercises/Debugging1stSyntaxError.js | 2 +- .../exercises/DebuggingLogicErrors1.js | 26 ++++++++++++++++++- .../exercises/DebuggingLogicErrors2.js | 7 +++-- .../exercises/DebuggingLogicErrors3.js | 6 +++-- .../exercises/DebuggingLogicErrors4.js | 4 ++- .../exercises/DebuggingLogicErrors5.js | 20 ++++++++------ .../exercises/DebuggingRuntimeErrors1.js | 6 +++-- .../exercises/DebuggingRuntimeErrors2.js | 2 +- .../exercises/DebuggingSyntaxErrors2.js | 4 +-- 9 files changed, 57 insertions(+), 20 deletions(-) diff --git a/errors-and-debugging/exercises/Debugging1stSyntaxError.js b/errors-and-debugging/exercises/Debugging1stSyntaxError.js index 365af5a964..4c3e57b91d 100644 --- a/errors-and-debugging/exercises/Debugging1stSyntaxError.js +++ b/errors-and-debugging/exercises/Debugging1stSyntaxError.js @@ -4,7 +4,7 @@ let launchReady = false; let fuelLevel = 17000; -if (fuelLevel >= 20000 { +if (fuelLevel >= 20000) {//MISSING CLOSING PARENTHESIS console.log('Fuel level cleared.'); launchReady = true; } else { diff --git a/errors-and-debugging/exercises/DebuggingLogicErrors1.js b/errors-and-debugging/exercises/DebuggingLogicErrors1.js index 1ad473f08d..f717502fab 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors1.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors1.js @@ -29,4 +29,28 @@ if (launchReady) { console.log('Liftoff!'); } else { console.log('Launch scrubbed.'); -} \ No newline at end of file +} + +//program runs no errors shown when running node DebuggingLogicErrors1.js +//fuel lvl is lss than 20000 and launch ready is false +//expected output 'launch scrubbed' +//current output: + /*Fuel level cleared. +10, 9, 8... +Fed parrot... +6, 5, 4... +Ignition... +3, 2, 1... +Liftoff! +*/ + +/* SOLUTION FROM TEXTBOOK TO COMPARE TO MY RESULTS +The shuttle should not have launched. However, the messages to the console tell a different story. Without any changes, the original code outputs: + + ```console + WARNING: Insufficient fuel! + Crew & computer cleared. + 10, 9, 8, 7, 6, 5, 4, 3, 2, 1... + Liftoff! + ``` + */ \ No newline at end of file diff --git a/errors-and-debugging/exercises/DebuggingLogicErrors2.js b/errors-and-debugging/exercises/DebuggingLogicErrors2.js index 160a0c2cd0..3624e80e92 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors2.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors2.js @@ -3,6 +3,7 @@ // Add console.log(launchReady) after this block, then run the program. //Given the fuelLevel value, should launchReady be true or false after the check? Is the program behaving as expected? +//FALSE + THE PROGRAM IS NOT RUNNING AS EXPECTED let launchReady = false; let fuelLevel = 17000; @@ -15,7 +16,8 @@ if (fuelLevel >= 20000) { } else { console.log('WARNING: Insufficient fuel!'); launchReady = false; -} +} +console.log(launchReady); // if (crewStatus && computerStatus === 'green'){ // console.log('Crew & computer cleared.'); @@ -30,4 +32,5 @@ if (fuelLevel >= 20000) { // console.log('Liftoff!'); // } else { // console.log('Launch scrubbed.'); -// } \ No newline at end of file +// } + diff --git a/errors-and-debugging/exercises/DebuggingLogicErrors3.js b/errors-and-debugging/exercises/DebuggingLogicErrors3.js index 023f2ab07d..9c721746e8 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors3.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors3.js @@ -4,6 +4,7 @@ // Given the values for crewStatus and computerStatus, should launchReady be true or false after the check? // Is the program behaving as expected? +//CREWSTATUS & COMPUTERSTATUS ARE TRUE BUT THE OUTPUT IS NOT EXPECTED BECAUSE LAUNCHREADY IS STILL FALSE let launchReady = false; // let fuelLevel = 17000; @@ -25,10 +26,11 @@ if (crewStatus && computerStatus === 'green'){ console.log('WARNING: Crew or computer not ready!'); launchReady = false; } - +console.log(launchReady); // if (launchReady) { // console.log('10, 9, 8, 7, 6, 5, 4, 3, 2, 1...'); // console.log('Liftoff!'); // } else { // console.log('Launch scrubbed.'); -// } \ No newline at end of file +// } + diff --git a/errors-and-debugging/exercises/DebuggingLogicErrors4.js b/errors-and-debugging/exercises/DebuggingLogicErrors4.js index dc9ac0af9d..654b662251 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors4.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors4.js @@ -3,6 +3,7 @@ // Given the values for fuelLevel, crewStatus and computerStatus, should launchReady be true or false? // Is the program behaving as expected? +//IF PROGRAM IS ONLY DEPENDANT ON CREWSTATUS AND COMPUTER STATUS LAUNCH OUTPUT WOULD BE EXPECTED RESULT BUT FUELLEVEL IS FALSE AND EXPECTED OUTPUT IS NOT CORRECT. let launchReady = false; let fuelLevel = 17000; @@ -34,4 +35,5 @@ console.log("launchReady = ", launchReady); // console.log('Liftoff!'); // } else { // console.log('Launch scrubbed.'); -// } \ No newline at end of file +// } + diff --git a/errors-and-debugging/exercises/DebuggingLogicErrors5.js b/errors-and-debugging/exercises/DebuggingLogicErrors5.js index 7eb908e769..8115b74def 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors5.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors5.js @@ -2,27 +2,31 @@ // Since the issue is with launchReady, ONE way to fix the logic error is to use a different variable to store the fuel check result. // Refactor the code to do this. Verify that your change works by updating the console.log statements. -let launchReady = false; +let launchReady = false;//dont change let fuelLevel = 17000; let crewStatus = true; let computerStatus = 'green'; -if (fuelLevel >= 20000) { +if (launchReady === true && fuelLevel >= 20000) { console.log('Fuel level cleared.'); - launchReady = true; + } else { console.log('WARNING: Insufficient fuel!'); - launchReady = false; } console.log("launchReady = ", launchReady); -if (crewStatus && computerStatus === 'green'){ +if (launchReady === true && crewStatus && computerStatus === 'green'){ console.log('Crew & computer cleared.'); - launchReady = true; } else { console.log('WARNING: Crew or computer not ready!'); - launchReady = false; } -console.log("launchReady = ", launchReady); \ No newline at end of file +console.log("launchReady = ", launchReady); + +if (launchReady === true && crewStatus && computerStatus === 'green') { + console.log("10, 9, 8, 7, 6, 5, 4, 3, 2, 1..."); + console.log("Liftoff!"); +} else { + console.log("Launch scrubbed"); +} \ No newline at end of file diff --git a/errors-and-debugging/exercises/DebuggingRuntimeErrors1.js b/errors-and-debugging/exercises/DebuggingRuntimeErrors1.js index e66e494a30..c7106f9c83 100644 --- a/errors-and-debugging/exercises/DebuggingRuntimeErrors1.js +++ b/errors-and-debugging/exercises/DebuggingRuntimeErrors1.js @@ -4,10 +4,12 @@ let launchReady = false; let fuelLevel = 17000; -if (fuellevel >= 20000) { +if (fuelLevel >= 20000) {//lowercase instead of camel case? console.log('Fuel level cleared.'); launchReady = true; } else { console.log('WARNING: Insufficient fuel!'); launchReady = false; -} \ No newline at end of file +} + +//fuel level is not defined \ No newline at end of file diff --git a/errors-and-debugging/exercises/DebuggingRuntimeErrors2.js b/errors-and-debugging/exercises/DebuggingRuntimeErrors2.js index a656080d25..f96decca2f 100644 --- a/errors-and-debugging/exercises/DebuggingRuntimeErrors2.js +++ b/errors-and-debugging/exercises/DebuggingRuntimeErrors2.js @@ -14,7 +14,7 @@ if (launchReady) { console.log("Fed parrot..."); console.log("6, 5, 4..."); console.log("Ignition..."); - consoul.log("3, 2, 1..."); + console.log("3, 2, 1...");//CONSOUL!?? console.log("Liftoff!"); } else { console.log("Launch scrubbed."); diff --git a/errors-and-debugging/exercises/DebuggingSyntaxErrors2.js b/errors-and-debugging/exercises/DebuggingSyntaxErrors2.js index b600339254..39cc4c4572 100644 --- a/errors-and-debugging/exercises/DebuggingSyntaxErrors2.js +++ b/errors-and-debugging/exercises/DebuggingSyntaxErrors2.js @@ -8,7 +8,7 @@ let launchReady = false; let crewStatus = true; let computerStatus = 'green'; -if (crewStatus &&& computerStatus === 'green'){ +if (crewStatus && computerStatus === 'green'){// 3 & SIGNS?? console.log('Crew & computer cleared.'); launchReady = true; } else { @@ -17,7 +17,7 @@ if (crewStatus &&& computerStatus === 'green'){ } if (launchReady) { - console.log(("10, 9, 8, 7, 6, 5, 4, 3, 2, 1..."); + console.log(("10, 9, 8, 7, 6, 5, 4, 3, 2, 1..."));//MISSING ENDING PARENTHESIS console.log("Fed parrot..."); console.log("Ignition..."); console.log("Liftoff!"); From 7dc34e1c049f59feef72e18ec4821a2f5d80a322 Mon Sep 17 00:00:00 2001 From: remi Date: Mon, 17 Jun 2024 23:35:35 -0400 Subject: [PATCH 05/12] CH 5 STUDIO V1 --- .../studio/data-variables-conditionals.js | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/booleans-and-conditionals/studio/data-variables-conditionals.js b/booleans-and-conditionals/studio/data-variables-conditionals.js index 6a15e146f4..924fd7f039 100644 --- a/booleans-and-conditionals/studio/data-variables-conditionals.js +++ b/booleans-and-conditionals/studio/data-variables-conditionals.js @@ -1,15 +1,89 @@ // Initialize Variables below +let date = "Monday 2019-03-18"; +let time = "10:05:34 AM"; +let astronautCount = 7; +let astronautStatus = "ready"; +let averageAstronautMassKg = 80.7; +let crewMassKg = astronautCount * averageAstronautMassKg; +let fuelMassKg = 760000; +let shuttleMassKg = 74842.31; +let totalMassKg = crewMassKg + fuelMassKg + shuttleMassKg; +let maximumMassLimit = 850000; +const fuelTempCelsius = -225; +const minimumFuelTemp = -300; +const fuelLevel = "100%"; +const weatherStatus = "clear"; +let preparedForLiftOff = true; +let readyCheck = 0; + + // add logic below to verify total number of astronauts for shuttle launch does not exceed 7 +if (astronautCount <= 7) { + console.log("Crew accounted for."); + //console.log("Ready Check ") + readyCheck += 1; +} + + + // add logic below to verify all astronauts are ready +if (astronautStatus === 'ready') { + console.log("Crew ready."); + readyCheck += 1; +} + // add logic below to verify the total mass does not exceed the maximum limit of 850000 + //if the totalMassKg is less than the maximumMassLimit of 850000 +if (totalMassKg < maximumMassLimit) { + console.log("Total Mass Kg within limit."); + readyCheck += 1; +} + // add logic below to verify the fuel temperature is within the appropriate range of -150 and -300 + // if the fuelTempCelsius is no less than -300 OR no greater than -150 + +if (fuelTempCelsius > -300 || fuelTempCelsius < -150) { + console.log("Fuel Temp in range."); + readyCheck += 1; +} // add logic below to verify the fuel level is at 100% +if (fuelLevel === "100%") { + console.log("Fuel Tank is Full."); + readyCheck += 1; +} + // add logic below to verify the weather status is clear +if (weatherStatus === "clear") { + console.log("Sky is Clear."); + readyCheck += 1; +} + // Verify shuttle launch can proceed based on above conditions +if (readyCheck === 6) { + console.log(`Ready Check: ${readyCheck}/6`); + console.log("All systems are a go! Initiating space shuttle launch sequence."); + console.log(""); + console.log("░I░N░I░T░I░A░L░I░Z░I░N░G░"); + console.log(`Date: ${date}`); + console.log(`Time: ${time}`); + console.log(`Astronaut Count: ${astronautCount}`); + console.log(`Crew Mass: ${crewMassKg} kg`); + console.log(`Fuel Mass: ${fuelMassKg} kg`); + console.log(`Shuttle Mass: ${shuttleMassKg} kg`); + console.log(`Total Mass: ${totalMassKg} kg`); + console.log(`Fuel Temperature: ${fuelTempCelsius} °C`); + console.log(`Weather Status: ${weatherStatus}`); + console.log("░I░N░I░T░I░A░T░I░N░G░ ░L░A░U░N░C░H░ ░S░E░Q░U░E░N░C░E░"); + console.log(""); + console.log("(人´∀`).☆.。.:* Have a safe trip astronauts! ☆彡"); +} else { + ("Scrub launch...") +} + From eedd5eadfbf9fde4263b4a510d7d908885fd6d2d Mon Sep 17 00:00:00 2001 From: remi Date: Thu, 20 Jun 2024 15:24:56 -0400 Subject: [PATCH 06/12] CH7 HW V1 --- .../exercises/part-one.js | 21 ++++++++++++++++++- .../exercises/part-three.js | 20 ++++++++++++++++++ .../exercises/part-two.js | 20 ++++++++++++++++-- 3 files changed, 58 insertions(+), 3 deletions(-) diff --git a/stringing-characters-together/exercises/part-one.js b/stringing-characters-together/exercises/part-one.js index 9295e4dd9f..049c13ed48 100644 --- a/stringing-characters-together/exercises/part-one.js +++ b/stringing-characters-together/exercises/part-one.js @@ -1,10 +1,29 @@ let num = 1001; -//Returns 'undefined'. +//Returns 'undefined'. DOES NOT GIVE LENGTH OF A NUMBER console.log(num.length); //Use type conversion to print the length (number of digits) of an integer. +let stringedNumber = num.toString(); +let lengthOfNum = stringedNumber.length; +console.log(stringedNumber.length); + + //Follow up: Print the number of digits in a DECIMAL value (e.g. num = 123.45 has 5 digits but a length of 6). +//THE PERIOD COUNTS IN THE LENGTH and must be modified to remove the period +let decVal = 1234.56 +let decValString = decVal.toString(); +let lengthOfD = decVal.length; +console.log(decValString.length); + +let decValWithout = decValString.replace('.', '');//removed the period from a string +console.log(decValWithout.length);//prints string excluding period + //Experiment! What if num could be EITHER an integer or a decimal? Add an if/else statement so your code can handle both cases. +if (String(num).includes('.')){ + console.log(String(num).length-1); + } else { + console.log(String(num).length); + } \ No newline at end of file diff --git a/stringing-characters-together/exercises/part-three.js b/stringing-characters-together/exercises/part-three.js index 8c310f1445..b0e60d987d 100644 --- a/stringing-characters-together/exercises/part-three.js +++ b/stringing-characters-together/exercises/part-three.js @@ -4,14 +4,34 @@ let language = 'JavaScript'; //1. Use string concatenation and two slice() methods to print 'JS' from 'JavaScript' +console.log(language.slice(0,1));//could also make a variable for j and s and then add them together +console.log(language.slice(4,5));//you would could add them together using ${} or print the two variables + + +console.log(language.slice(0,1) + language.slice(4,5)); + //2. Without using slice(), use method chaining to accomplish the same thing. +console.log(language.substring(0,1)); +console.log(language.substring(4,5)); + +let initials = (language.substring(0,1) + language.slice(4,5)); +console.log(initials); + //3. Use bracket notation and a template literal to print, "The abbreviation for 'JavaScript' is 'JS'." +//kind of confused here idk why the brackets keep printing? +//is the solution wrong? or mu understanding of bracket notation is not correct? +console.log("The abbreviation for [" + language + "] is [" + initials + "]."); //4. Just for fun, try chaining 3 or more methods together, and then print the result. +let forFun = (language.slice(0,1) + language.substring(4,5) + ", " + language.length + ", " + language.toLowerCase()); +console.log(forFun); //Part Three section Two //1. Use the string methods you know to print 'Title Case' from the string 'title case'. let notTitleCase = 'title case'; +let realCase = notTitleCase.replace("title case", "Tital Case"); + +console.log(realCase); \ No newline at end of file diff --git a/stringing-characters-together/exercises/part-two.js b/stringing-characters-together/exercises/part-two.js index a06e9094dc..ebb1aeeb33 100644 --- a/stringing-characters-together/exercises/part-two.js +++ b/stringing-characters-together/exercises/part-two.js @@ -3,18 +3,20 @@ let dna = " TCG-TAC-gaC-TAC-CGT-CAG-ACT-TAa-CcA-GTC-cAt-AGA-GCT "; // First, print out the dna strand in it's current state. +console.log(dna); //1) Use the .trim() method to remove the leading and trailing whitespace, then print the result. -console.log(/* Your code here. */); +console.log(dna.trim()); //2) Change all of the letters in the dna string to UPPERCASE, then print the result. -console.log(); +console.log(dna.toLocaleUpperCase()); //3) Note that after applying the methods above, the original, flawed string is still stored in dna. To fix this, we need to reassign the changes to back to dna. //Apply these fixes to your code so that console.log(dna) prints the DNA strand in UPPERCASE with no whitespace. +dna = dna.trim().toLocaleUpperCase(); console.log(dna); //Part Two Section Two @@ -22,11 +24,25 @@ console.log(dna); let dnaTwo = "TCG-TAC-GAC-TAC-CGT-CAG-ACT-TAA-CCA-GTC-CAT-AGA-GCT"; //1) Replace the gene "GCT" with "AGG", and then print the altered strand. +dnaTwo = dnaTwo.replace('GCT','AGG'); +console.log(dnaTwo); //2) Look for the gene "CAT" with ``indexOf()``. If found print, "CAT gene found", otherwise print, "CAT gene NOT found". +if (dnaTwo.indexOf('CAT') !== -1) { + console.log("CAT FOUND"); +} else { + console.log("CAT NOT found"); +} //3) Use .slice() to print out the fifth gene (set of 3 characters) from the DNA strand. +console.log(dnaTwo.slice(16,19)); + //4) Use a template literal to print, "The DNA strand is ___ characters long." +console.log(`The DNA strand is ${dnaTwo.length} characters long.`); + //5) Just for fun, apply methods to ``dna`` and use another template literal to print, 'taco cat'. +let food = "taco cat"; +console.log(dna.toLowerCase); +console.log(`oh i just can't wait to eat a ${food}`); \ No newline at end of file From b5c397d819f32247b826ebdb220e2dff979529a5 Mon Sep 17 00:00:00 2001 From: remi Date: Thu, 20 Jun 2024 22:38:35 -0400 Subject: [PATCH 07/12] WK 3 STUDIO V.5 --- arrays/studio/node_modules/.package-lock.json | 15 + .../node_modules/readline-sync/LICENSE-MIT | 22 + .../readline-sync/README-Deprecated.md | 89 + .../node_modules/readline-sync/README.md | 1827 +++++++++++++++++ .../node_modules/readline-sync/lib/encrypt.js | 24 + .../node_modules/readline-sync/lib/read.cs.js | 123 ++ .../node_modules/readline-sync/lib/read.ps1 | 128 ++ .../node_modules/readline-sync/lib/read.sh | 137 ++ .../readline-sync/lib/readline-sync.js | 1302 ++++++++++++ .../node_modules/readline-sync/package.json | 41 + arrays/studio/package-lock.json | 20 + arrays/studio/string-modification.js | 4 + 12 files changed, 3732 insertions(+) create mode 100644 arrays/studio/node_modules/.package-lock.json create mode 100644 arrays/studio/node_modules/readline-sync/LICENSE-MIT create mode 100644 arrays/studio/node_modules/readline-sync/README-Deprecated.md create mode 100644 arrays/studio/node_modules/readline-sync/README.md create mode 100644 arrays/studio/node_modules/readline-sync/lib/encrypt.js create mode 100644 arrays/studio/node_modules/readline-sync/lib/read.cs.js create mode 100644 arrays/studio/node_modules/readline-sync/lib/read.ps1 create mode 100644 arrays/studio/node_modules/readline-sync/lib/read.sh create mode 100644 arrays/studio/node_modules/readline-sync/lib/readline-sync.js create mode 100644 arrays/studio/node_modules/readline-sync/package.json create mode 100644 arrays/studio/package-lock.json diff --git a/arrays/studio/node_modules/.package-lock.json b/arrays/studio/node_modules/.package-lock.json new file mode 100644 index 0000000000..fb73a102e2 --- /dev/null +++ b/arrays/studio/node_modules/.package-lock.json @@ -0,0 +1,15 @@ +{ + "name": "studio", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/readline-sync": { + "version": "1.4.9", + "resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.9.tgz", + "integrity": "sha512-mp5h1N39kuKbCRGebLPIKTBOhuDw55GaNg5S+K9TW9uDAS1wIHpGUc2YokdUMZJb8GqS49sWmWEDijaESYh0Hg==", + "engines": { + "node": ">= 0.8.0" + } + } + } +} diff --git a/arrays/studio/node_modules/readline-sync/LICENSE-MIT b/arrays/studio/node_modules/readline-sync/LICENSE-MIT new file mode 100644 index 0000000000..e1469d6044 --- /dev/null +++ b/arrays/studio/node_modules/readline-sync/LICENSE-MIT @@ -0,0 +1,22 @@ +Copyright (c) 2018 anseki + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/arrays/studio/node_modules/readline-sync/README-Deprecated.md b/arrays/studio/node_modules/readline-sync/README-Deprecated.md new file mode 100644 index 0000000000..25128a5c2a --- /dev/null +++ b/arrays/studio/node_modules/readline-sync/README-Deprecated.md @@ -0,0 +1,89 @@ +# readlineSync + +## Deprecated Methods and Options + +The readlineSync current version is fully compatible with older version. +The following methods and options are deprecated. + +### `setPrint` method + +Use the [`print`](README.md#basic_options-print) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({print: value}); +``` + +instead of: + +```js +readlineSync.setPrint(value); +``` + +### `setPrompt` method + +Use the [`prompt`](README.md#basic_options-prompt) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({prompt: value}); +``` + +instead of: + +```js +readlineSync.setPrompt(value); +``` + +### `setEncoding` method + +Use the [`encoding`](README.md#basic_options-encoding) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({encoding: value}); +``` + +instead of: + +```js +readlineSync.setEncoding(value); +``` + +### `setMask` method + +Use the [`mask`](README.md#basic_options-mask) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({mask: value}); +``` + +instead of: + +```js +readlineSync.setMask(value); +``` + +### `setBufferSize` method + +Use the [`bufferSize`](README.md#basic_options-buffersize) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({bufferSize: value}); +``` + +instead of: + +```js +readlineSync.setBufferSize(value); +``` + +### `noEchoBack` option + +Use [`hideEchoBack`](README.md#basic_options-hideechoback) option instead of it. + +### `noTrim` option + +Use [`keepWhitespace`](README.md#basic_options-keepwhitespace) option instead of it. diff --git a/arrays/studio/node_modules/readline-sync/README.md b/arrays/studio/node_modules/readline-sync/README.md new file mode 100644 index 0000000000..cbe7c13778 --- /dev/null +++ b/arrays/studio/node_modules/readline-sync/README.md @@ -0,0 +1,1827 @@ +# readlineSync + +[![npm](https://img.shields.io/npm/v/readline-sync.svg)](https://www.npmjs.com/package/readline-sync) [![GitHub issues](https://img.shields.io/github/issues/anseki/readline-sync.svg)](https://github.com/anseki/readline-sync/issues) [![dependencies](https://img.shields.io/badge/dependencies-No%20dependency-brightgreen.svg)](package.json) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE-MIT) + +Synchronous [Readline](http://nodejs.org/api/readline.html) for interactively running to have a conversation with the user via a console(TTY). + +readlineSync tries to let your script have a conversation with the user via a console, even when the input/output stream is redirected like `your-script bar.log`. + + + +
Basic OptionsUtility MethodsPlaceholders
+ +* Simple case: + +```js +var readlineSync = require('readline-sync'); + +// Wait for user's response. +var userName = readlineSync.question('May I have your name? '); +console.log('Hi ' + userName + '!'); + +// Handle the secret text (e.g. password). +var favFood = readlineSync.question('What is your favorite food? ', { + hideEchoBack: true // The typed text on screen is hidden by `*` (default). +}); +console.log('Oh, ' + userName + ' loves ' + favFood + '!'); +``` + +```console +May I have your name? CookieMonster +Hi CookieMonster! +What is your favorite food? **** +Oh, CookieMonster loves tofu! +``` + +* Get the user's response by a single key without the Enter key: + +```js +var readlineSync = require('readline-sync'); +if (readlineSync.keyInYN('Do you want this module?')) { + // 'Y' key was pressed. + console.log('Installing now...'); + // Do something... +} else { + // Another key was pressed. + console.log('Searching another...'); + // Do something... +} +``` + +* Let the user choose an item from a list: + +```js +var readlineSync = require('readline-sync'), + animals = ['Lion', 'Elephant', 'Crocodile', 'Giraffe', 'Hippo'], + index = readlineSync.keyInSelect(animals, 'Which animal?'); +console.log('Ok, ' + animals[index] + ' goes to your room.'); +``` + +```console +[1] Lion +[2] Elephant +[3] Crocodile +[4] Giraffe +[5] Hippo +[0] CANCEL + +Which animal? [1...5 / 0]: 2 +Ok, Elephant goes to your room. +``` + +* An UI like the Range Slider: +(Press `Z` or `X` key to change a value, and Space Bar to exit) + +```js +var readlineSync = require('readline-sync'), + MAX = 60, MIN = 0, value = 30, key; +console.log('\n\n' + (new Array(20)).join(' ') + + '[Z] <- -> [X] FIX: [SPACE]\n'); +while (true) { + console.log('\x1B[1A\x1B[K|' + + (new Array(value + 1)).join('-') + 'O' + + (new Array(MAX - value + 1)).join('-') + '| ' + value); + key = readlineSync.keyIn('', + {hideEchoBack: true, mask: '', limit: 'zx '}); + if (key === 'z') { if (value > MIN) { value--; } } + else if (key === 'x') { if (value < MAX) { value++; } } + else { break; } +} +console.log('\nA value the user requested: ' + value); +``` + +![sample](screen_03.gif) + +* Handle the commands repeatedly, such as the shell interface: + +```js +readlineSync.promptCLLoop({ + add: function(target, into) { + console.log(target + ' is added into ' + into + '.'); + // Do something... + }, + remove: function(target) { + console.log(target + ' is removed.'); + // Do something... + }, + bye: function() { return true; } +}); +console.log('Exited'); +``` + +```console +> add pic01.png archive +pic01.png is added into archive. +> delete pic01.png +Requested command is not available. +> remove pic01.png +pic01.png is removed. +> bye +Exited +``` + +## Installation + +```shell +npm install readline-sync +``` + +## Quick Start + +**How does the user input?** + +- [Type a reply to a question, and press the Enter key](#quick_start-a) (A) +- [Type a keyword like a command in prompt, and press the Enter key](#quick_start-b) (B) +- [Press a single key without the Enter key](#quick_start-c) (C) + +**(A) What does the user input?** + +- [E-mail address](#utility_methods-questionemail) +- [New password](#utility_methods-questionnewpassword) +- [Integer number](#utility_methods-questionint) +- [Floating-point number](#utility_methods-questionfloat) +- [Local file/directory path](#utility_methods-questionpath) +- [Others](#basic_methods-question) + +**(B) What does your script do?** + +- [Receive a parsed command-name and arguments](#utility_methods-promptcl) +- [Receive an input repeatedly](#utility_methods-promptloop) +- [Receive a parsed command-name and arguments repeatedly](#utility_methods-promptclloop) +- [Receive an input with prompt that is similar to that of the user's shell](#utility_methods-promptsimshell) +- [Others](#basic_methods-prompt) + +**(C) What does the user do?** + +- [Say "Yes" or "No"](#utility_methods-keyinyn) +- [Say "Yes" or "No" explicitly](#utility_methods-keyinynstrict) +- [Make the running of script continue when ready](#utility_methods-keyinpause) +- [Choose an item from a list](#utility_methods-keyinselect) +- [Others](#basic_methods-keyin) + +## Basic Methods + +These are used to control details of the behavior. It is recommended to use the [Utility Methods](#utility_methods) instead of Basic Methods if it satisfy your request. + +### `question` + +```js +answer = readlineSync.question([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then return the input from the user after it has been typed and the Enter key was pressed. +You can specify an `options` (see [Basic Options](#basic_options)) to control the behavior (e.g. refusing unexpected input, avoiding trimming white spaces, etc.). **If you let the user input the secret text (e.g. password), you should consider [`hideEchoBack`](#basic_options-hideechoback) option.** + +The `query` may be string, or may not be (e.g. number, Date, Object, etc.). It is converted to string (i.e. `toString` method is called) before it is displayed. (see [Note](#note) also) +It can include the [placeholders](#placeholders). + +For example: + +```js +program = readlineSync.question('Which program starts do you want? ', { + defaultInput: 'firefox' +}); +``` + +### `prompt` + +```js +input = readlineSync.prompt([options]) +``` + +Display a prompt-sign (see [`prompt`](#basic_options-prompt) option) to the user, and then return the input from the user after it has been typed and the Enter key was pressed. +You can specify an `options` (see [Basic Options](#basic_options)) to control the behavior (e.g. refusing unexpected input, avoiding trimming white spaces, etc.). + +For example: + +```js +while (true) { + command = readlineSync.prompt(); + // Do something... +} +``` + +### `keyIn` + +```js +pressedKey = readlineSync.keyIn([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then return a character as a key immediately it was pressed by the user, **without pressing the Enter key**. Note that the user has no chance to change the input. +You can specify an `options` (see [Basic Options](#basic_options)) to control the behavior (e.g. ignoring keys except some keys, checking target key, etc.). + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. + +For example: + +```js +menuId = readlineSync.keyIn('Hit 1...5 key: ', {limit: '$<1-5>'}); +``` + +### `setDefaultOptions` + +```js +currentDefaultOptions = readlineSync.setDefaultOptions([newDefaultOptions]) +``` + +Change the [Default Options](#basic_options) to the values of properties of `newDefaultOptions` Object. +All it takes is to specify options that you want change, because unspecified options are not updated. + +## Basic Options + +[`prompt`](#basic_options-prompt), [`hideEchoBack`](#basic_options-hideechoback), [`mask`](#basic_options-mask), [`limit`](#basic_options-limit), [`limitMessage`](#basic_options-limitmessage), [`defaultInput`](#basic_options-defaultinput), [`trueValue`, `falseValue`](#basic_options-truevalue_falsevalue), [`caseSensitive`](#basic_options-casesensitive), [`keepWhitespace`](#basic_options-keepwhitespace), [`encoding`](#basic_options-encoding), [`bufferSize`](#basic_options-buffersize), [`print`](#basic_options-print), [`history`](#basic_options-history), [`cd`](#basic_options-cd) + +An `options` Object can be specified to the methods to control the behavior of readlineSync. The options that were not specified to the methods are got from the Default Options. You can change the Default Options by [`setDefaultOptions`](#basic_methods-setdefaultoptions) method anytime, and it is kept until a current process is exited. +Specify the options that are often used to the Default Options, and specify temporary options to the methods. + +For example: + +```js +readlineSync.setDefaultOptions({limit: ['green', 'yellow', 'red']}); +a1 = readlineSync.question('Which color of signal? '); // Input is limited to 3 things. +a2 = readlineSync.question('Which color of signal? '); // It's limited yet. +a3 = readlineSync.question('What is your favorite color? ', {limit: null}); // It's unlimited temporarily. +a4 = readlineSync.question('Which color of signal? '); // It's limited again. +readlineSync.setDefaultOptions({limit: ['beef', 'chicken']}); +a5 = readlineSync.question('Beef or Chicken? '); // Input is limited to new 2 things. +a6 = readlineSync.question('And you? '); // It's limited to 2 things yet. +``` + +The Object as `options` can have following properties. + +### `prompt` + +_For `prompt*` methods only_ +*Type:* string or others +*Default:* `'> '` + +Set the prompt-sign that is displayed to the user by `prompt*` methods. For example you see `> ` that is Node.js's prompt-sign when you run `node` on the command line. +This may be string, or may not be (e.g. number, Date, Object, etc.). It is converted to string every time (i.e. `toString` method is called) before it is displayed. (see [Note](#note) also) +It can include the [placeholders](#placeholders). + +For example: + +```js +readlineSync.setDefaultOptions({prompt: '$ '}); +``` + +```js +// Display the memory usage always. +readlineSync.setDefaultOptions({ + prompt: { // Simple Object that has toString method. + toString: function() { + var rss = process.memoryUsage().rss; + return '[' + (rss > 1024 ? Math.round(rss / 1024) + 'k' : rss) + 'b]$ '; + } + } +}); +``` + +```console +[13148kb]$ foo +[13160kb]$ bar +[13200kb]$ +``` + +### `hideEchoBack` + +*Type:* boolean +*Default:* `false` + +If `true` is specified, hide the secret text (e.g. password) which is typed by user on screen by the mask characters (see [`mask`](#basic_options-mask) option). + +For example: + +```js +password = readlineSync.question('PASSWORD: ', {hideEchoBack: true}); +console.log('Login ...'); +``` + +```console +PASSWORD: ******** +Login ... +``` + +### `mask` + +*Type:* string +*Default:* `'*'` + +Set the mask characters that are shown instead of the secret text (e.g. password) when `true` is specified to [`hideEchoBack`](#basic_options-hideechoback) option. If you want to show nothing, specify `''`. (But it might be not user friendly in some cases.) +**Note:** In some cases (e.g. when the input stream is redirected on Windows XP), `'*'` or `''` might be used whether other one is specified. + +For example: + +```js +secret = readlineSync.question('Please whisper sweet words: ', { + hideEchoBack: true, + mask: require('chalk').magenta('\u2665') +}); +``` + +![sample](screen_02.gif) + +### `limit` + +Limit the user's input. +The usage differ depending on the method. + +#### For `question*` and `prompt*` methods + +*Type:* string, number, RegExp, function or Array +*Default:* `[]` + +Accept only the input that matches value that is specified to this. If the user input others, display a string that is specified to [`limitMessage`](#basic_options-limitmessage) option, and wait for reinput. + +* The string is compared with the input. It is affected by [`caseSensitive`](#basic_options-casesensitive) option. +* The number is compared with the input that is converted to number by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`. And it interprets `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`. +* The RegExp tests the input. +* The function that returns a boolean to indicate whether it matches is called with the input. + +One of above or an Array that includes multiple things (or Array includes Array) can be specified. + +For example: + +```js +command = readlineSync.prompt({limit: ['add', 'remove', /^clear( all)?$/]}); +// ** But `promptCL` method should be used instead of this. ** +``` + +```js +file = readlineSync.question('Text File: ', {limit: /\.txt$/i}); +// ** But `questionPath` method should be used instead of this. ** +``` + +```js +ip = readlineSync.question('IP Address: ', {limit: function(input) { + return require('net').isIP(input); // Valid IP Address +}}); +``` + +```js +availableActions = []; +if (!blockExists()) { availableActions.push('jump'); } +if (isLarge(place)) { availableActions.push('run'); } +if (isNew(shoes)) { availableActions.push('kick'); } +if (isNearby(enemy)) { availableActions.push('punch'); } +action = readlineSync.prompt({limit: availableActions}); +// ** But `promptCL` method should be used instead of this. ** +``` + +#### For `keyIn*` method + +*Type:* string, number or Array +*Default:* `[]` + +Accept only the key that matches value that is specified to this, ignore others. +Specify the characters as the key. All strings or Array of those are decomposed into single characters. For example, `'abcde'` or `['a', 'bc', ['d', 'e']]` are the same as `['a', 'b', 'c', 'd', 'e']`. +These strings are compared with the input. It is affected by [`caseSensitive`](#basic_options-casesensitive) option. + +The [placeholders](#placeholders) like `'$'` are replaced to an Array that is the character list like `['a', 'b', 'c', 'd', 'e']`. + +For example: + +```js +direction = readlineSync.keyIn('Left or Right? ', {limit: 'lr'}); // 'l' or 'r' +``` + +```js +dice = readlineSync.keyIn('Roll the dice, What will the result be? ', + {limit: '$<1-6>'}); // range of '1' to '6' +``` + +### `limitMessage` + +_For `question*` and `prompt*` methods only_ +*Type:* string +*Default:* `'Input another, please.$<( [)limit(])>'` + +Display this to the user when the [`limit`](#basic_options-limit) option is specified and the user input others. +The [placeholders](#placeholders) can be included. + +For example: + +```js +file = readlineSync.question('Name of Text File: ', { + limit: /\.txt$/i, + limitMessage: 'Sorry, $ is not text file.' +}); +``` + +### `defaultInput` + +_For `question*` and `prompt*` methods only_ +*Type:* string +*Default:* `''` + +If the user input empty text (i.e. pressed the Enter key only), return this. + +For example: + +```js +lang = readlineSync.question('Which language? ', {defaultInput: 'javascript'}); +``` + +### `trueValue`, `falseValue` + +*Type:* string, number, RegExp, function or Array +*Default:* `[]` + +If the input matches `trueValue`, return `true`. If the input matches `falseValue`, return `false`. In any other case, return the input. + +* The string is compared with the input. It is affected by [`caseSensitive`](#basic_options-casesensitive) option. +* The number is compared with the input that is converted to number by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`. And it interprets `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`. Note that in `keyIn*` method, the input is every time one character (i.e. the number that is specified must be an integer within the range of `0` to `9`). +* The RegExp tests the input. +* The function that returns a boolean to indicate whether it matches is called with the input. + +One of above or an Array that includes multiple things (or Array includes Array) can be specified. + +For example: + +```js +answer = readlineSync.question('How do you like it? ', { + trueValue: ['yes', 'yeah', 'yep'], + falseValue: ['no', 'nah', 'nope'] +}); +if (answer === true) { + console.log('Let\'s go!'); +} else if (answer === false) { + console.log('Oh... It\'s ok...'); +} else { + console.log('Sorry. What does "' + answer + '" you said mean?'); +} +``` + +### `caseSensitive` + +*Type:* boolean +*Default:* `false` + +By default, the string comparisons are case-insensitive (i.e. `a` equals `A`). If `true` is specified, it is case-sensitive, the cases are not ignored (i.e. `a` is different from `A`). +It affects: [`limit`](#basic_options-limit), [`trueValue`](#basic_options-truevalue_falsevalue), [`falseValue`](#basic_options-truevalue_falsevalue), some [placeholders](#placeholders), and some [Utility Methods](#utility_methods). + +### `keepWhitespace` + +_For `question*` and `prompt*` methods only_ +*Type:* boolean +*Default:* `false` + +By default, remove the leading and trailing white spaces from the input text. If `true` is specified, don't remove those. + +### `encoding` + +*Type:* string +*Default:* `'utf8'` + +Set the encoding method of the input and output. + +### `bufferSize` + +_For `question*` and `prompt*` methods only_ +*Type:* number +*Default:* `1024` + +When readlineSync reads from a console directly (without [external program](#note-reading_by_external_program)), use a size `bufferSize` buffer. +Even if the input by user exceeds it, it's usually no problem, because the buffer is used repeatedly. But some platforms's (e.g. Windows) console might not accept input that exceeds it. And set an enough size. +Note that this might be limited by [version of Node.js](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_alloc_size_fill_encoding) and environment running your script (Big buffer size is usually not required). (See also: [issue](https://github.com/nodejs/node/issues/4660), [PR](https://github.com/nodejs/node/pull/4682)) + +### `print` + +*Type:* function or `undefined` +*Default:* `undefined` + +Call the specified function with every output. The function is given two arguments, `display` as an output text, and a value of [`encoding`](#basic_options-encoding) option. + +For example: + +* Pass the plain texts to the Logger (e.g. [log4js](https://github.com/nomiddlename/log4js-node)), after clean the colored texts. + +![sample](screen_01.png) + +```js +var readlineSync = require('readline-sync'), + chalk = require('chalk'), + log4js = require('log4js'), + logger, user, pw, command; + +log4js.configure({appenders: [{type: 'file', filename: 'fooApp.log'}]}); +logger = log4js.getLogger('fooApp'); + +readlineSync.setDefaultOptions({ + print: function(display, encoding) + { logger.info(chalk.stripColor(display)); }, // Remove ctrl-chars. + prompt: chalk.red.bold('> ') +}); + +console.log(chalk.black.bold.bgYellow(' Your Account ')); +user = readlineSync.question(chalk.gray.underline(' USER NAME ') + ' : '); +pw = readlineSync.question(chalk.gray.underline(' PASSWORD ') + ' : ', + {hideEchoBack: true}); +// Authorization ... +console.log(chalk.green('Welcome, ' + user + '!')); +command = readlineSync.prompt(); +``` + +* Output a conversation to a file when an output stream is redirected to record those into a file like `your-script >foo.log`. That is, a conversation isn't outputted to `foo.log` without this code. + +```js +readlineSync.setDefaultOptions({ + print: function(display, encoding) + { process.stdout.write(display, encoding); } +}); +var name = readlineSync.question('May I have your name? '); +var loc = readlineSync.question('Hi ' + name + '! Where do you live? '); +``` + +* Let somebody hear our conversation in real time. +It just uses a fifo with above sample code that was named `conv.js`. + +Another terminal: + +```shell +mkfifo /tmp/fifo +cat /tmp/fifo +``` + +My terminal: + +```shell +node conv.js >/tmp/fifo +``` + +```console +May I have your name? Oz +Hi Oz! Where do you live? Emerald City +``` + +And then, another terminal shows this synchronously: + +```console +May I have your name? Oz +Hi Oz! Where do you live? Emerald City +``` + +### `history` + +_For `question*` and `prompt*` methods only_ +*Type:* boolean +*Default:* `true` + +readlineSync supports a history expansion feature that is similar to that of the shell. If `false` is specified, disable this feature. +*It keeps a previous input only.* That is, only `!!`, `!-1`, `!!:p` and `!-1:p` like bash or zsh etc. are supported. + +* `!!` or `!-1`: Return a previous input. +* `!!:p` or `!-1:p`: Display a previous input but do not return it, and wait for reinput. + +For example: + +```js +while (true) { + input = readlineSync.prompt(); + console.log('-- You said "' + input + '"'); +} +``` + +```console +> hello +-- You said "hello" +> !! +hello +-- You said "hello" +> !!:p +hello +> bye +-- You said "bye" +``` + +### `cd` + +_For `question*` and `prompt*` methods only_ +*Type:* boolean +*Default:* `false` + +readlineSync supports the changing the current working directory feature that is similar to the `cd` and `pwd` commands in the shell. If `true` is specified, enable this feature. +This helps the user when you let the user input the multiple local files or directories. +It supports `cd` and `pwd` commands. + +* `cd `: Change the current working directory to ``. The `` can include `~` as the home directory. +* `pwd`: Display the current working directory. + +When these were input, do not return, and wait for reinput. + +For example: + +```js +while (true) { + file = readlineSync.questionPath('File: '); + console.log('-- Specified file is ' + file); +} +``` + +```console +File: cd foo-dir/bar-dir +File: pwd +/path/to/foo-dir/bar-dir +File: file-a.js +-- Specified file is /path/to/foo-dir/bar-dir/file-a.js +File: file-b.png +-- Specified file is /path/to/foo-dir/bar-dir/file-b.png +File: file-c.html +-- Specified file is /path/to/foo-dir/bar-dir/file-c.html +``` + +## Utility Methods + +[`questionEMail`](#utility_methods-questionemail), [`questionNewPassword`](#utility_methods-questionnewpassword), [`questionInt`](#utility_methods-questionint), [`questionFloat`](#utility_methods-questionfloat), [`questionPath`](#utility_methods-questionpath), [`promptCL`](#utility_methods-promptcl), [`promptLoop`](#utility_methods-promptloop), [`promptCLLoop`](#utility_methods-promptclloop), [`promptSimShell`](#utility_methods-promptsimshell), [`keyInYN`](#utility_methods-keyinyn), [`keyInYNStrict`](#utility_methods-keyinynstrict), [`keyInPause`](#utility_methods-keyinpause), [`keyInSelect`](#utility_methods-keyinselect) + +These are convenient methods that are extended [Basic Methods](#basic_methods) to be used easily. + +### `questionEMail` + +```js +email = readlineSync.questionEMail([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only a valid e-mail address, and then return it after the Enter key was pressed. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Input e-mail address: '`. + +**Note:** The valid e-mail address requirement is a willful violation of [RFC5322](http://tools.ietf.org/html/rfc5322), this is defined in [HTML5](http://www.w3.org/TR/html5/forms.html). This works enough to prevent the user mistaking. If you want to change it, specify [`limit`](#basic_options-limit) option. + +For example: + +```js +email = readlineSync.questionEMail(); +console.log('-- E-mail is ' + email); +``` + +```console +Input e-mail address: abc +Input valid e-mail address, please. +Input e-mail address: mail@example.com +-- E-mail is mail@example.com +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`limit`](#basic_options-limit) | RegExp by [HTML5](http://www.w3.org/TR/html5/forms.html) | +| [`limitMessage`](#basic_options-limitmessage) | `'Input valid e-mail address, please.'` | +| [`trueValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`falseValue`](#basic_options-truevalue_falsevalue) | `null` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
maskdefaultInputcaseSensitiveencodingbufferSize
printhistory
+ +### `questionNewPassword` + +```js +password = readlineSync.questionNewPassword([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only a valid password, and then request same one again, and then return it after the Enter key was pressed. +It's the password, or something that is the secret text like the password. +You can specify the valid password requirement to the options. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Input new password: '`. + +**Note:** Only the form of password is checked. Check it more if you want. For example, [zxcvbn](https://github.com/dropbox/zxcvbn) is password strength estimation library. + +For example: + +```js +password = readlineSync.questionNewPassword(); +console.log('-- Password is ' + password); +``` + +```console +Input new password: ************ +It can include: 0...9, A...Z, a...z, !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ +And the length must be: 12...24 +Input new password: ************* +Reinput a same one to confirm it: ************* +It differs from first one. Hit only the Enter key if you want to retry from first one. +Reinput a same one to confirm it: ************* +-- Password is _my_password_ +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `true` | +| [`mask`](#basic_options-mask) | `'*'` | +| [`limitMessage`](#basic_options-limitmessage) | `'It can include: $\nAnd the length must be: $'` | +| [`trueValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`falseValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`caseSensitive`](#basic_options-casesensitive) | `true` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
defaultInputkeepWhitespaceencodingbufferSizeprint
+ +And the following additional options are available. + +##### `charlist` + +*Type:* string +*Default:* `'$'` + +A string as the characters that can be included in the password. For example, if `'abc123'` is specified, the passwords that include any character other than these 6 characters are refused. +The [placeholders](#placeholders) like `'$'` are replaced to the characters like `'abcde'`. + +For example, let the user input a password that is created with alphabet and some symbols: + +```js +password = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$#$@%'}); +``` + +##### `min`, `max` + +*Type:* number +*Default:* `min`: `12`, `max`: `24` + +`min`: A number as a minimum length of the password. +`max`: A number as a maximum length of the password. + +##### `confirmMessage` + +*Type:* string or others +*Default:* `'Reinput a same one to confirm it: '` + +A message that lets the user input the same password again. +It can include the [placeholders](#placeholders). +If this is not string, it is converted to string (i.e. `toString` method is called). + +##### `unmatchMessage` + +*Type:* string or others +*Default:* `'It differs from first one. Hit only the Enter key if you want to retry from first one.'` + +A warning message that is displayed when the second input did not match first one. +This is converted the same as the [`confirmMessage`](#utility_methods-questionnewpassword-options-confirmmessage) option. + +#### Additional Placeholders + +The following additional [placeholder](#placeholders) parameters are available. + +##### `charlist` + +A current value of [`charlist`](#utility_methods-questionnewpassword-options-charlist) option that is converted to human readable if possible. (e.g. `'A...Z'`) + +##### `length` + +A current value of [`min` and `max`](#utility_methods-questionnewpassword-options-min_max) option that is converted to human readable. (e.g. `'12...24'`) + +### `questionInt` + +```js +numInt = readlineSync.questionInt([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only an input that can be interpreted as an integer, and then return the number (not string) after the Enter key was pressed. +This parses the input as much as possible by `parseInt()`. For example, it interprets `' 5 '`, `'5.6'`, `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. + +#### Options + +The following option has independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`limitMessage`](#basic_options-limitmessage) | `'Input valid number, please.'` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
hideEchoBackmaskdefaultInputencodingbufferSize
printhistory
+ +### `questionFloat` + +```js +numFloat = readlineSync.questionFloat([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only an input that can be interpreted as a floating-point number, and then return the number (not string) after the Enter key was pressed. +This parses the input as much as possible by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. + +#### Options + +The following option has independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`limitMessage`](#basic_options-limitmessage) | `'Input valid number, please.'` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
hideEchoBackmaskdefaultInputencodingbufferSize
printhistory
+ +### `questionPath` + +```js +path = readlineSync.questionPath([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only a valid local file or directory path, and then return an absolute path after the Enter key was pressed. +The `~` that is input by the user is replaced to the home directory. +You can specify the valid local file or directory path requirement to the options. And you can make it create a new file or directory when it doesn't exist. + +It is recommended to use this method with the [`cd`](#basic_options-cd) option. (Default: `true`) + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Input path (you can "cd" and "pwd"): '`. + +For example: + +```js +sourceFile = readlineSync.questionPath('Read from: ', { + isFile: true +}); +console.log('-- sourceFile: ' + sourceFile); + +saveDir = readlineSync.questionPath('Save to: ', { + isDirectory: true, + exists: null, + create: true +}); +console.log('-- saveDir: ' + saveDir); +``` + +```console +Read from: ~/fileA +No such file or directory: /home/user/fileA +Input valid path, please. +Read from: pwd +/path/to/work +Read from: cd ~/project-1 +Read from: fileA +-- sourceFile: /home/user/project-1/fileA +Save to: ~/deploy/data +-- saveDir: /home/user/deploy/data +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`limitMessage`](#basic_options-limitmessage) | `'$Input valid path, please.$<( Min:)min>$<( Max:)max>'` | +| [`history`](#basic_options-history) | `true` | +| [`cd`](#basic_options-cd) | `true` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
maskdefaultInputencodingbufferSizeprint
+ +And the following additional options are available. + +**Note:** It does not check the coherency about a combination of the options as the path requirement. For example, the `{exists: false, isFile: true}` never check that it is a file because it is limited to the path that does not exist. + +##### `exists` + +*Type:* boolean or others +*Default:* `true` + +If `true` is specified, accept only a file or directory path that exists. If `false` is specified, accept only a file or directory path that does *not* exist. +In any other case, the existence is not checked. + +##### `min`, `max` + +*Type:* number or others +*Default:* `undefined` + +`min`: A number as a minimum size of the file that is accepted. +`max`: A number as a maximum size of the file that is accepted. +If it is not specified or `0` is specified, the size is not checked. (A size of directory is `0`.) + +##### `isFile`, `isDirectory` + +*Type:* boolean +*Default:* `false` + +`isFile`: If `true` is specified, accept only a file path. +`isDirectory`: If `true` is specified, accept only a directory path. + +##### `validate` + +*Type:* function or `undefined` +*Default:* `undefined` + +If a function that returns `true` or an error message is specified, call it with a path that was input, and accept the input when the function returned `true`. +If the function returned a string as an error message, that message is got by the [`error`](#utility_methods-questionpath-additional_placeholders-error) additional [placeholder](#placeholders) parameter. +A path that was input is parsed before it is passed to the function. `~` is replaced to a home directory, and a path is converted to an absolute path. +This is also a return value from this method. + +For example, accept only PNG file or tell it to the user: + +```js +imageFile = readlineSync.questionPath('Image File: ', { + validate: function(path) { return /\.png$/i.test(path) || 'It is not PNG'; } +}); +``` + +##### `create` + +*Type:* boolean +*Default:* `false` + +If `true` is specified, create a file or directory as a path that was input when it doesn't exist. If `true` is specified to the [`isDirectory`](#utility_methods-questionpath-options-isfile_isdirectory) option, create a directory, otherwise a file. +It does not affect the existence check. Therefore, you can get a new file or directory path anytime by specifying: `{exists: false, create: true}` + +#### Additional Placeholders + +The following additional [placeholder](#placeholders) parameters are available. + +##### `error` + +An error message when the input was not accepted. +This value is set by readlineSync, or the function that was specified to [`validate`](#utility_methods-questionpath-options-validate) option. + +##### `min`, `max` + +A current value of [`min` and `max`](#utility_methods-questionpath-options-min_max) option. + +### `promptCL` + +```js +argsArray = readlineSync.promptCL([commandHandler[, options]]) +``` + +Display a prompt-sign (see [`prompt`](#basic_options-prompt) option) to the user, and then consider the input as a command-line and parse it, and then return a result after the Enter key was pressed. +A return value is an Array that includes the tokens that were parsed. It parses the input from the user as the command-line, and it interprets whitespaces, quotes, etc., and it splits it to tokens properly. Usually, a first element of the Array is command-name, and remaining elements are arguments. + +For example: + +```js +argsArray = readlineSync.promptCL(); +console.log(argsArray.join('\n')); +``` + +```console +> command arg "arg" " a r g " "" 'a"r"g' "a""rg" "arg +command +arg +arg + a r g + +a"r"g +arg +arg +``` + +#### `commandHandler` + +By using the `commandHandler` argument, this method will come into its own. Specifying the Object to this argument has the more merit. And it has the more merit for [`promptCLLoop`](#utility_methods-promptclloop) method. + +If a function is specified to `commandHandler` argument, it is just called with a parsed Array as an argument list of the function. And `this` is an original input string, in the function. + +For example, the following 2 codes work same except that `this` is enabled in the second one: + +```js +argsArray = readlineSync.promptCL(); +if (argsArray[0] === 'add') { + console.log(argsArray[1] + ' is added.'); +} else if (argsArray[0] === 'copy') { + console.log(argsArray[1] + ' is copied to ' + argsArray[2] + '.'); +} +``` + +```js +readlineSync.promptCL(function(command, arg1, arg2) { + console.log('You want to: ' + this); // All of command-line. + if (command === 'add') { + console.log(arg1 + ' is added.'); + } else if (command === 'copy') { + console.log(arg1 + ' is copied to ' + arg2 + '.'); + } +}); +``` + +If an Object that has properties named as the command-name is specified, the command-name is interpreted, and a function as the value of matched property is called. A function is chosen properly by handling case of the command-name in accordance with the [`caseSensitive`](#basic_options-casesensitive) option. +The function is called with a parsed Array that excludes a command-name (i.e. first element is removed from the Array) as an argument list of the function. +That is, a structure of the `commandHandler` Object looks like: + +```js +{ + commandA: function(arg) { ... }, // commandA requires one argument. + commandB: function(arg1, arg2) { ... }, // readlineSync doesn't care those. + commandC: function() { ... } // Of course, it can also ignore all. +} +``` + +readlineSync just receives the arguments from the user and passes those to these functions without checking. The functions may have to check whether the required argument was input by the user, and more validate those. + +For example, the following code works same to the above code: + +```js +readlineSync.promptCL({ + add: function(element) { // It's called by also "ADD", "Add", "aDd", etc.. + console.log(element + ' is added.'); + }, + copy: function(from, to) { + console.log(from + ' is copied to ' + to + '.'); + } +}); +``` + +If the matched property is not found in the Object, a `_` property is chosen, and the function as the value of this property is called with a parsed Array as an argument list of the function. Note that this includes a command-name. That is, the function looks like `function(command, arg1, arg2, ...) { ... }`. +And if the Object doesn't have a `_` property, any command that the matched property is not found in the Object is refused. + +For example: + +```js +readlineSync.promptCL({ + copy: function(from, to) { // command-name is not included. + console.log(from + ' is copied to ' + to + '.'); + }, + _: function(command) { // command-name is included. + console.log('Sorry, ' + command + ' is not available.'); + } +}); +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`limitMessage`](#basic_options-limitmessage) | `'Requested command is not available.'` | +| [`caseSensitive`](#basic_options-casesensitive) | `false` | +| [`history`](#basic_options-history) | `true` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
promptmaskdefaultInputencodingbufferSize
printcd
+ +### `promptLoop` + +```js +readlineSync.promptLoop(inputHandler[, options]) +``` + +Display a prompt-sign (see [`prompt`](#basic_options-prompt) option) to the user, and then call `inputHandler` function with the input from the user after it has been typed and the Enter key was pressed. Do these repeatedly until `inputHandler` function returns `true`. + +For example, the following 2 codes work same: + +```js +while (true) { + input = readlineSync.prompt(); + console.log('-- You said "' + input + '"'); + if (input === 'bye') { + break; + } +} +console.log('It\'s exited from loop.'); +``` + +```js +readlineSync.promptLoop(function(input) { + console.log('-- You said "' + input + '"'); + return input === 'bye'; +}); +console.log('It\'s exited from loop.'); +``` + +```console +> hello +-- You said "hello" +> good morning +-- You said "good morning" +> bye +-- You said "bye" +It's exited from loop. +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`trueValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`falseValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`caseSensitive`](#basic_options-casesensitive) | `false` | +| [`history`](#basic_options-history) | `true` | + +The other options work as shown in the [Basic Options](#basic_options) section. + +### `promptCLLoop` + +```js +readlineSync.promptCLLoop([commandHandler[, options]]) +``` + +Execute [`promptCL`](#utility_methods-promptcl) method repeatedly until chosen [`commandHandler`](#utility_methods-promptcl-commandhandler) returns `true`. +The [`commandHandler`](#utility_methods-promptcl-commandhandler) may be a function that is called like: + +```js +exit = allCommands(command, arg1, arg2, ...); +``` + +or an Object that has the functions that are called like: + +```js +exit = foundCommand(arg1, arg2, ...); +``` + +See [`promptCL`](#utility_methods-promptcl) method for details. +This method looks like a combination of [`promptCL`](#utility_methods-promptcl) method and [`promptLoop`](#utility_methods-promptloop) method. + +For example: + +```js +readlineSync.promptCLLoop({ + add: function(element) { + console.log(element + ' is added.'); + }, + copy: function(from, to) { + console.log(from + ' is copied to ' + to + '.'); + }, + bye: function() { return true; } +}); +console.log('It\'s exited from loop.'); +``` + +```console +> add "New Hard Disk" +New Hard Disk is added. +> move filesOnOld "New Hard Disk" +Requested command is not available. +> copy filesOnOld "New Hard Disk" +filesOnOld is copied to New Hard Disk. +> bye +It's exited from loop. +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`limitMessage`](#basic_options-limitmessage) | `'Requested command is not available.'` | +| [`caseSensitive`](#basic_options-casesensitive) | `false` | +| [`history`](#basic_options-history) | `true` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
promptmaskdefaultInputencodingbufferSize
printcd
+ +### `promptSimShell` + +```js +input = readlineSync.promptSimShell([options]) +``` + +Display a prompt-sign that is similar to that of the user's shell to the user, and then return the input from the user after it has been typed and the Enter key was pressed. +This method displays a prompt-sign like: + +On Windows: + +```shell +C:\Users\User\Path\To\Directory> +``` + +On others: + +```shell +user@host:~/path/to/directory$ +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`history`](#basic_options-history) | `true` | + +The other options other than [`prompt`](#basic_options-prompt) option work as shown in the [Basic Options](#basic_options) section. + +### `keyInYN` + +```js +boolYesOrEmpty = readlineSync.keyInYN([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then return a boolean or an empty string immediately a key was pressed by the user, **without pressing the Enter key**. Note that the user has no chance to change the input. +This method works like the `window.confirm` method of web browsers. A return value means "Yes" or "No" the user said. It differ depending on the pressed key: + +* `Y`: `true` +* `N`: `false` +* other: `''` + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Are you sure? '`. + +The keys other than `Y` and `N` are also accepted (If you want to know a user's wish explicitly, use [`keyInYNStrict`](#utility_methods-keyinynstrict) method). Therefore, if you let the user make an important decision (e.g. files are removed), check whether the return value is not *falsy*. That is, a default is "No". + +For example: + +```js +if (!readlineSync.keyInYN('Do you want to install this?')) { + // Key that is not `Y` was pressed. + process.exit(); +} +// Do something... +``` + +Or if you let the user stop something that must be done (e.g. something about the security), check whether the return value is `false` explicitly. That is, a default is "Yes". + +For example: + +```js +// Don't use `(!readlineSync.keyInYN())`. +if (readlineSync.keyInYN('Continue virus scan?') === false) { + // `N` key was pressed. + process.exit(); +} +// Continue... +``` + +#### Options + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
encodingprint
+ +And the following additional option is available. + +##### `guide` + +*Type:* boolean +*Default:* `true` + +If `true` is specified, a string `'[y/n]'` as guide for the user is added to `query`. And `':'` is moved to the end of `query`, or it is added. + +For example: + +```js +readlineSync.keyInYN('Do you like me?'); // No colon +readlineSync.keyInYN('Really? :'); // Colon already exists +``` + +``` console +Do you like me? [y/n]: y +Really? [y/n]: y +``` + +### `keyInYNStrict` + +```js +boolYes = readlineSync.keyInYNStrict([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only `Y` or `N` key, and then return a boolean immediately it was pressed by the user, **without pressing the Enter key**. Note that the user has no chance to change the input. +This method works like the `window.confirm` method of web browsers. A return value means "Yes" or "No" the user said. It differ depending on the pressed key: + +* `Y`: `true` +* `N`: `false` + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Are you sure? '`. + +A key other than `Y` and `N` is not accepted. That is, a return value has no default. Therefore, the user has to tell an own wish explicitly. If you want to know a user's wish easily, use [`keyInYN`](#utility_methods-keyinyn) method. + +This method works same to [`keyInYN`](#utility_methods-keyinyn) method except that this accept only `Y` or `N` key (Therefore, a return value is boolean every time). The options also work same to [`keyInYN`](#utility_methods-keyinyn) method. + +### `keyInPause` + +```js +readlineSync.keyInPause([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then just wait for a key to be pressed by the user. +This method works like the `window.alert` method of web browsers. This is used to make the running of script pause and show something to the user, or wait for the user to be ready. +By default, any key is accepted. You can change this behavior by specifying [`limit`](#basic_options-limit) option (e.g. accept only a Space Bar). + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Continue...'`. + +For example: + +```js +// Have made the preparations for something... +console.log('==== Information of Your Computer ===='); +console.log(info); // This can be `query`. +readlineSync.keyInPause(); +console.log('It\'s executing now...'); +// Do something... +``` + +```console +==== Information of Your Computer ==== +FOO: 123456 +BAR: abcdef +Continue... (Hit any key) +It's executing now... +``` + +#### Options + +The following option has independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`limit`](#basic_options-limit) | `null` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
caseSensitiveencodingprint
+ +And the following additional option is available. + +##### `guide` + +*Type:* boolean +*Default:* `true` + +If `true` is specified, a string `'(Hit any key)'` as guide for the user is added to `query`. + +For example: + +```js +readlineSync.keyInPause('It\'s pausing now...'); +``` + +``` console +It's pausing now... (Hit any key) +``` + +### `keyInSelect` + +```js +index = readlineSync.keyInSelect(items[, query[, options]]) +``` + +Display the list that was created with the `items` Array, and the `query` to the user if it's specified, and then return the number as an index of the `items` Array immediately it was chosen by pressing a key by the user, **without pressing the Enter key**. Note that the user has no chance to change the input. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Choose one from list: '`. + +The minimum length of `items` Array is 1 and maximum length is 35. These elements are displayed as item list. A key to let the user choose an item is assigned to each item automatically in sequence like "1, 2, 3 ... 9, A, B, C ...". A number as an index of the `items` Array that corresponds to a chosen item by the user is returned. + +**Note:** Even if the `items` Array has only less than 35 items, a long Array that forces an user to scroll the list may irritate the user. Remember, the user might be in a console environment that doesn't support scrolling the screen. If you want to use a long `items` Array (e.g. more than 10 items), you should consider a "Pagination". (See [example](https://github.com/anseki/readline-sync/issues/60#issuecomment-324533678).) + +For example: + +```js +frameworks = ['Express', 'hapi', 'flatiron', 'MEAN.JS', 'locomotive']; +index = readlineSync.keyInSelect(frameworks, 'Which framework?'); +console.log(frameworks[index] + ' is enabled.'); +``` + +```console +[1] Express +[2] hapi +[3] flatiron +[4] MEAN.JS +[5] locomotive +[0] CANCEL + +Which framework? [1...5 / 0]: 2 +hapi is enabled. +``` + +#### Options + +The following option has independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
maskencodingprint
+ +And the following additional options are available. + +##### `guide` + +*Type:* boolean +*Default:* `true` + +If `true` is specified, a string like `'[1...5]'` as guide for the user is added to `query`. And `':'` is moved to the end of `query`, or it is added. This is the key list that corresponds to the item list. + +##### `cancel` + +*Type:* boolean, string or others +*Default:* `'CANCEL'` + +If a value other than `false` is specified, an item to let the user tell "cancel" is added to the item list. "[0] CANCEL" (default) is displayed, and if `0` key is pressed, `-1` is returned. +You can specify a label of this item other than `'CANCEL'`. A string such as `'Go back'` (empty string `''` also), something that is converted to string such as `Date`, a string that includes [placeholder](#placeholders) such as `'Next $ items'` are accepted. + +#### Additional Placeholders + +The following additional [placeholder](#placeholders) parameters are available. + +##### `itemsCount` + +A length of a current `items` Array. + +For example: + +```js +items = ['item-A', 'item-B', 'item-C', 'item-D', 'item-E']; +index = readlineSync.keyInSelect(items, null, + {cancel: 'Show more than $ items'}); +``` + +```console +[1] item-A +[2] item-B +[3] item-C +[4] item-D +[5] item-E +[0] Show more than 5 items +``` + +##### `firstItem` + +A first item in a current `items` Array. + +For example: + +```js +index = readlineSync.keyInSelect(items, 'Choose $ or another: '); +``` + +##### `lastItem` + +A last item in a current `items` Array. + +For example: + +```js +items = ['January', 'February', 'March', 'April', 'May', 'June']; +index = readlineSync.keyInSelect(items, null, + {cancel: 'In after $'}); +``` + +```console +[1] January +[2] February +[3] March +[4] April +[5] May +[6] June +[0] In after June +``` + +## Placeholders + +[`hideEchoBack`, `mask`, `defaultInput`, `caseSensitive`, `keepWhitespace`, `encoding`, `bufferSize`, `history`, `cd`, `limit`, `trueValue`, `falseValue`](#placeholders-parameters-hideechoback_mask_defaultinput_casesensitive_keepwhitespace_encoding_buffersize_history_cd_limit_truevalue_falsevalue), [`limitCount`, `limitCountNotZero`](#placeholders-parameters-limitcount_limitcountnotzero), [`lastInput`](#placeholders-parameters-lastinput), [`history_mN`](#placeholders-parameters-historymn), [`cwd`, `CWD`, `cwdHome`](#placeholders-parameters-cwd_cwd_cwdhome), [`date`, `time`, `localeDate`, `localeTime`](#placeholders-parameters-date_time_localedate_localetime), [`C1-C2`](#placeholders-parameters-c1_c2) + +The placeholders in the text are replaced to another string. + +For example, the [`limitMessage`](#basic_options-limitmessage) option to display a warning message that means that the command the user requested is not available: + +```js +command = readlineSync.prompt({ + limit: ['add', 'remove'], + limitMessage: '$ is not available.' +}); +``` + +```console +> delete +delete is not available. +``` + +The placeholders can be included in: + +* `query` argument +* [`prompt`](#basic_options-prompt) and [`limitMessage`](#basic_options-limitmessage) options +* [`limit` option for `keyIn*` method](#basic_options-limit-for_keyin_method) and [`charlist`](#utility_methods-questionnewpassword-options-charlist) option for [`questionNewPassword`](#utility_methods-questionnewpassword) method ([`C1-C2`](#placeholders-parameters-c1_c2) parameter only) +* And some additional options for the [Utility Methods](#utility_methods). + +### Syntax + +``` +$ +``` + +Or + +``` +$<(text1)parameter(text2)> +``` + +The placeholder is replaced to a string that is got by a `parameter`. +Both the `(text1)` and `(text2)` are optional. +A more added `'$'` at the left of the placeholder is used as an escape character, it disables a placeholder. For example, `'$$'` is replaced to `'$'`. If you want to put a `'$'` which is *not* an escape character at the left of a placeholder, specify it like `'$<($)bufferSize>'`, then it is replaced to `'$1024'`. + +At the each position of `'(text1)'` and `'(text2)'`, `'text1'` and `'text2'` are put when a string that was got by a `parameter` has more than 0 length. If that got string is `''`, a placeholder with or without `'(text1)'` and `'(text2)'` is replaced to `''`. + +For example, a warning message that means that the command the user requested is not available: + +```js +command = readlineSync.prompt({ + limit: ['add', 'remove'], + limitMessage: 'Refused $ you requested. Please input another.' +}); +``` + +```console +> give-me-car +Refused give-me-car you requested. Please input another. +``` + +It looks like no problem. +But when the user input nothing (hit only the Enter key), and then a message is displayed: + +```console +> +Refused you requested. Please input another. +``` + +This goes well: + +```js +command = readlineSync.prompt({ + limit: ['add', 'remove'], + limitMessage: 'Refused $. Please input another.' +}); +``` + +```console +> +Refused . Please input another. +``` + +(May be more better: `'$<(Refused )lastInput( you requested. )>Please input another.'`) + +**Note:** The syntax `${parameter}` of older version is still supported, but this should not be used because it may be confused with template string syntax of ES6. And this will not be supported in due course of time. + +### Parameters + +The following parameters are available. And some additional parameters are available in the [Utility Methods](#utility_methods). + +#### `hideEchoBack`, `mask`, `defaultInput`, `caseSensitive`, `keepWhitespace`, `encoding`, `bufferSize`, `history`, `cd`, `limit`, `trueValue`, `falseValue` + +A current value of each option. +It is converted to human readable if possible. The boolean value is replaced to `'on'` or `'off'`, and the Array is replaced to the list of only string and number elements. +And in the `keyIn*` method, the parts of the list as characters sequence are suppressed. For example, when `['a', 'b', 'c', 'd', 'e']` is specified to the [`limit`](#basic_options-limit) option, `'$'` is replaced to `'a...e'`. If `true` is specified to the [`caseSensitive`](#basic_options-casesensitive) option, the characters are converted to lower case. + +For example: + +```js +input = readlineSync.question( + 'Input something or the Enter key as "$": ', + {defaultInput: 'hello'} +); +``` + +```console +Input something or the Enter key as "hello": +``` + +#### `limitCount`, `limitCountNotZero` + +A length of a current value of the [`limit`](#basic_options-limit) option. +When the value of the [`limit`](#basic_options-limit) option is empty, `'$'` is replaced to `'0'`, `'$'` is replaced to `''`. + +For example: + +```js +action = readlineSync.question( + 'Choose action$<( from )limitCountNotZero( actions)>: ', + {limit: availableActions} +); +``` + +```console +Choose action from 5 actions: +``` + +#### `lastInput` + +A last input from the user. +In any case, this is saved. + +For example: + +```js +command = readlineSync.prompt({ + limit: availableCommands, + limitMessage: '$ is not available.' +}); +``` + +```console +> wrong-command +wrong-command is not available. +``` + +#### `history_mN` + +When the history expansion feature is enabled (see [`history`](#basic_options-history) option), a current command line minus `N`. +*This feature keeps the previous input only.* That is, only `history_m1` is supported. + +For example: + +```js +while (true) { + input = readlineSync.question('Something$<( or "!!" as ")history_m1(")>: '); + console.log('-- You said "' + input + '"'); +} +``` + +```console +Something: hello +-- You said "hello" +Something or "!!" as "hello": !! +hello +-- You said "hello" +``` + +#### `cwd`, `CWD`, `cwdHome` + +A current working directory. + +* `cwd`: A full-path +* `CWD`: A directory name +* `cwdHome`: A path that includes `~` as the home directory + +For example, like bash/zsh: + +```js +command = readlineSync.prompt({prompt: '[$]$ '}); +``` + +```console +[~/foo/bar]$ +``` + +#### `date`, `time`, `localeDate`, `localeTime` + +A string as current date or time. + +* `date`: A date portion +* `time`: A time portion +* `localeDate`: A locality sensitive representation of the date portion based on system settings +* `localeTime`: A locality sensitive representation of the time portion based on system settings + +For example: + +```js +command = readlineSync.prompt({prompt: '[$]> '}); +``` + +```console +[04/21/2015]> +``` + +#### `C1-C2` + +_For [`limit` option for `keyIn*` method](#basic_options-limit-for_keyin_method) and [`charlist`](#utility_methods-questionnewpassword-options-charlist) option for [`questionNewPassword`](#utility_methods-questionnewpassword) method only_ + +A character list. +`C1` and `C2` are each single character as the start and the end. A sequence in ascending or descending order of characters ranging from `C1` to `C2` is created. For example, `'$'` is replaced to `'abcde'`. `'$<5-1>'` is replaced to `'54321'`. + +For example, let the user input a password that is created with alphabet: + +```js +password = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$'}); +``` + +See also [`limit` option for `keyIn*` method](#basic_options-limit-for_keyin_method). + +## Special method `getRawInput` + +```js +rawInput = readlineSync.getRawInput() +``` + +Return a raw input data of last method. +When the input was terminated with no data, a `NULL` is inserted to the data. + +This might contain control-codes (e.g. `LF`, `CR`, `EOF`, etc.), therefore, it might be used to get `^D` that was input. But you should understand each environments for that. Or, **you should not use this** if your script is used in multiple environments. +For example, when the user input `EOF` (`^D` in Unix like system, `^Z` in Windows), `x1A` (`EOF`) is returned in Windows, and `x00` (`NULL`) is returned in Unix like system. And `x04` (`EOT`) is returned in Unix like system with raw-mode. And also, when [external program](#note-reading_by_external_program) is used, nothing is returned. See also [Control characters](#note-control_characters). +You may examine each environment and you must test your script very much, if you want to handle the raw input data. + +## With Task Runner + +The easy way to control a flow of the task runner by the input from the user: + +* [Grunt](http://gruntjs.com/) plugin: [grunt-confirm](https://github.com/anseki/grunt-confirm) +* [gulp](http://gulpjs.com/) plugin: [gulp-confirm](https://github.com/anseki/gulp-confirm) + +If you want to control a flow of the task runner (e.g. [Grunt](http://gruntjs.com/)), call readlineSync in a task callback that is called by the task runner. Then a flow of tasks is paused and it is controlled by the user. + +For example, by using [grunt-task-helper](https://github.com/anseki/grunt-task-helper): + +```console +$ grunt +Running "fileCopy" task +Files already exist: + file-a.png + file-b.js +Overwrite? [y/n]: y +file-a.png copied. +file-b.js copied. +Done. +``` + +`Gruntfile.js` + +```js +grunt.initConfig({ + taskHelper: { + fileCopy: { + options: { + handlerByTask: function() { + // Abort the task if user don't want it. + return readlineSync.keyInYN('Overwrite?'); + }, + filesArray: [] + }, + ... + } + }, + copy: { + fileCopy: { + files: '<%= taskHelper.fileCopy.options.filesArray %>' + } + } +}); +``` + +## Note + +### Platforms + +TTY interfaces are different by the platforms. If the platform doesn't support the interactively reading from TTY, an error is thrown. + +```js +try { + answer = readlineSync.question('What is your favorite food? '); +} catch (e) { + console.error(e); + process.exit(1); +} +``` + +### Control characters + +TTY interfaces are different by the platforms. In some environments, ANSI escape sequences might be ignored. For example, in non-POSIX TTY such as Windows CMD does not support it (that of Windows 8 especially has problems). Since readlineSync does not use Node.js library that emulates POSIX TTY (but that is still incomplete), those characters may be not parsed. Then, using ANSI escape sequences is not recommended if you will support more environments. +Also, control characters user input might be not accepted or parsed. That behavior differs depending on the environment. And current Node.js does not support controlling a readline system library. + +### Reading by external program + +readlineSync tries to read from a console by using the external program if it is needed (e.g. when the input stream is redirected on Windows XP). And if the running Node.js doesn't support the [Synchronous Process Execution](http://nodejs.org/api/child_process.html#child_process_synchronous_process_creation) (i.e. Node.js v0.10-), readlineSync uses "piping via files" for the synchronous execution. +As everyone knows, "piping via files" is no good. It blocks the event loop and a process. It might make the your script be slow. + +Why did I choose it? : + +* Good modules (native addon) for the synchronous execution exist, but node-gyp can't compile those in some platforms or Node.js versions. +* I think that the security is important more than the speed. Some modules have problem about security. Those don't protect the data. I think that the speed is not needed usually, because readlineSync is used while user types keys. + +## Deprecated methods and options + +See [README-Deprecated.md](README-Deprecated.md). diff --git a/arrays/studio/node_modules/readline-sync/lib/encrypt.js b/arrays/studio/node_modules/readline-sync/lib/encrypt.js new file mode 100644 index 0000000000..1a99135579 --- /dev/null +++ b/arrays/studio/node_modules/readline-sync/lib/encrypt.js @@ -0,0 +1,24 @@ +/* + * readlineSync + * https://github.com/anseki/readline-sync + * + * Copyright (c) 2018 anseki + * Licensed under the MIT license. + */ + +var cipher = require('crypto').createCipher( + process.argv[2] /*algorithm*/, process.argv[3] /*password*/), + stdin = process.stdin, + stdout = process.stdout, + crypted = ''; + +stdin.resume(); +stdin.setEncoding('utf8'); +stdin.on('data', function(d) { + crypted += cipher.update(d, 'utf8', 'hex'); +}); +stdin.on('end', function() { + stdout.write(crypted + cipher.final('hex'), 'binary', function() { + process.exit(0); + }); +}); diff --git a/arrays/studio/node_modules/readline-sync/lib/read.cs.js b/arrays/studio/node_modules/readline-sync/lib/read.cs.js new file mode 100644 index 0000000000..0dcd521b9d --- /dev/null +++ b/arrays/studio/node_modules/readline-sync/lib/read.cs.js @@ -0,0 +1,123 @@ +/* jshint wsh:true */ + +/* + * readlineSync + * https://github.com/anseki/readline-sync + * + * Copyright (c) 2018 anseki + * Licensed under the MIT license. + */ + +var + FSO_ForReading = 1, FSO_ForWriting = 2, + PS_MSG = 'Microsoft Windows PowerShell is required.' + + ' https://technet.microsoft.com/en-us/library/hh847837.aspx', + + input = '', fso, tty, + options = (function(conf) { + var options = {}, arg, args =// Array.prototype.slice.call(WScript.Arguments), + (function() { + var args = [], i, iLen; + for (i = 0, iLen = WScript.Arguments.length; i < iLen; i++) + { args.push(WScript.Arguments(i)); } + return args; + })(), + confLc = {}, key; + + function decodeArg(arg) { + return arg.replace(/#(\d+);/g, function(str, charCode) { + return String.fromCharCode(+charCode); + }); + } + + for (key in conf) { + if (conf.hasOwnProperty(key)) + { confLc[key.toLowerCase()] = {key: key, type: conf[key]}; } + } + + while (typeof(arg = args.shift()) === 'string') { + if (!(arg = (arg.match(/^\-+(.+)$/) || [])[1])) { continue; } + arg = arg.toLowerCase(); + if (confLc[arg]) { + options[confLc[arg].key] = + confLc[arg].type === 'boolean' ? true : + confLc[arg].type === 'string' ? args.shift() : null; + } + } + for (key in conf) { + if (conf.hasOwnProperty(key) && conf[key] === 'string') { + if (typeof options[key] !== 'string') { options[key] = ''; } + else { options[key] = decodeArg(options[key]); } + } + } + return options; + })({ + display: 'string', + displayOnly: 'boolean', + keyIn: 'boolean', + hideEchoBack: 'boolean', + mask: 'string' + }); + +if (!options.hideEchoBack && !options.keyIn) { + if (options.display) { writeTTY(options.display); } + if (!options.displayOnly) { input = readByFSO(); } +} else if (options.hideEchoBack && !options.keyIn && !options.mask) { + if (options.display) { writeTTY(options.display); } + if (!options.displayOnly) { input = readByPW(); } +} else { + WScript.StdErr.WriteLine(PS_MSG); + WScript.Quit(1); +} + +WScript.StdOut.Write('\'' + input + '\''); + +WScript.Quit(); + +function writeTTY(text) { + try { + tty = tty || getFso().OpenTextFile('CONOUT$', FSO_ForWriting, true); + tty.Write(text); + } catch (e) { + WScript.StdErr.WriteLine('TTY Write Error: ' + e.number + + '\n' + e.description + '\n' + PS_MSG); + WScript.Quit(e.number || 1); + } +} + +function readByFSO() { + var text; + try { + text = getFso().OpenTextFile('CONIN$', FSO_ForReading).ReadLine(); + } catch (e) { + WScript.StdErr.WriteLine('TTY Read Error: ' + e.number + + '\n' + e.description + '\n' + PS_MSG); + WScript.Quit(e.number || 1); + } + return text; +} + +// TTY must be STDIN that is not redirected and not piped. +function readByPW() { + var text; + try { + text = WScript.CreateObject('ScriptPW.Password').GetPassword() + // Bug? Illegal data may be returned when user types before initializing. + .replace(/[\u4000-\u40FF]/g, function(chr) { + var charCode = chr.charCodeAt(0); + return charCode >= 0x4020 && charCode <= 0x407F ? + String.fromCharCode(charCode - 0x4000) : ''; + }); + } catch (e) { + WScript.StdErr.WriteLine('ScriptPW.Password Error: ' + e.number + + '\n' + e.description + '\n' + PS_MSG); + WScript.Quit(e.number || 1); + } + writeTTY('\n'); + return text; +} + +function getFso() { + if (!fso) { fso = new ActiveXObject('Scripting.FileSystemObject'); } + return fso; +} diff --git a/arrays/studio/node_modules/readline-sync/lib/read.ps1 b/arrays/studio/node_modules/readline-sync/lib/read.ps1 new file mode 100644 index 0000000000..a1d6bcfdd5 --- /dev/null +++ b/arrays/studio/node_modules/readline-sync/lib/read.ps1 @@ -0,0 +1,128 @@ +# readlineSync +# https://github.com/anseki/readline-sync +# +# Copyright (c) 2018 anseki +# Licensed under the MIT license. + +Param( + [string] $display, + [switch] $displayOnly, + [switch] $keyIn, + [switch] $hideEchoBack, + [string] $mask, + [string] $limit, + [switch] $caseSensitive +) + +$ErrorActionPreference = 'Stop' # for cmdlet +trap { + # `throw $_` and `Write-Error $_` return exit-code 0 + $Host.UI.WriteErrorLine($_) + exit 1 +} + +function decodeArg ($arg) { + [Regex]::Replace($arg, '#(\d+);', { [char][int] $args[0].Groups[1].Value }) +} + +$options = @{} +foreach ($arg in @('display', 'displayOnly', 'keyIn', 'hideEchoBack', 'mask', 'limit', 'caseSensitive')) { + $options.Add($arg, (Get-Variable $arg -ValueOnly)) +} +$argList = New-Object string[] $options.Keys.Count +$options.Keys.CopyTo($argList, 0) +foreach ($arg in $argList) { + if ($options[$arg] -is [string] -and $options[$arg]) + { $options[$arg] = decodeArg $options[$arg] } +} + +[string] $inputTTY = '' +[bool] $silent = -not $options.display -and + $options.keyIn -and $options.hideEchoBack -and -not $options.mask +[bool] $isCooked = -not $options.hideEchoBack -and -not $options.keyIn + +# Instant method that opens TTY without CreateFile via P/Invoke in .NET Framework +# **NOTE** Don't include special characters of DOS in $command when $getRes is True. +# [string] $cmdPath = $Env:ComSpec +# [string] $psPath = 'powershell.exe' +function execWithTTY ($command, $getRes = $False, $throwError = $False) { + if ($getRes) { + $res = (cmd.exe /C "CON powershell.exe -Command -" + if ($LastExitCode -ne 0) { + if ($throwError) { throw $LastExitCode } + else { exit $LastExitCode } + } + } +} + +function writeTTY ($text) { + execWithTTY ('Write-Host (''' + + (($text -replace '''', '''''') -replace '[\r\n]', '''+"`n"+''') + ''') -NoNewline') +} + +if ($options.display) { + writeTTY $options.display +} +if ($options.displayOnly) { return "''" } + +if (-not $options.keyIn -and $options.hideEchoBack -and $options.mask -eq '*') { + # It fails when it's not ready. + try { + $inputTTY = execWithTTY ('$text = Read-Host -AsSecureString;' + + '$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($text);' + + '[Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)') $True $True + return '''' + $inputTTY + '''' + } catch {} # ignore +} + +if ($options.keyIn) { $reqSize = 1 } + +if ($options.keyIn -and $options.limit) { + $limitPtn = '[^' + $options.limit + ']' +} + +while ($True) { + if (-not $isCooked) { + $chunk = [char][int] (execWithTTY '[int] [Console]::ReadKey($True).KeyChar' $True) + } else { + $chunk = execWithTTY 'Read-Host' $True + $chunk += "`n" + } + + if ($chunk -and $chunk -match '^(.*?)[\r\n]') { + $chunk = $Matches[1] + $atEol = $True + } else { $atEol = $False } + + # other ctrl-chars + if ($chunk) { $chunk = $chunk -replace '[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '' } + if ($chunk -and $limitPtn) { + if ($options.caseSensitive) { $chunk = $chunk -creplace $limitPtn, '' } + else { $chunk = $chunk -ireplace $limitPtn, '' } + } + + if ($chunk) { + if (-not $isCooked) { + if (-not $options.hideEchoBack) { + writeTTY $chunk + } elseif ($options.mask) { + writeTTY ($options.mask * $chunk.Length) + } + } + $inputTTY += $chunk + } + + if ((-not $options.keyIn -and $atEol) -or + ($options.keyIn -and $inputTTY.Length -ge $reqSize)) { break } +} + +if (-not $isCooked -and -not $silent) { execWithTTY 'Write-Host ''''' } # new line + +return "'$inputTTY'" diff --git a/arrays/studio/node_modules/readline-sync/lib/read.sh b/arrays/studio/node_modules/readline-sync/lib/read.sh new file mode 100644 index 0000000000..fc6d6e5775 --- /dev/null +++ b/arrays/studio/node_modules/readline-sync/lib/read.sh @@ -0,0 +1,137 @@ +# readlineSync +# https://github.com/anseki/readline-sync +# +# Copyright (c) 2018 anseki +# Licensed under the MIT license. + +# Use perl for compatibility of sed/awk of GNU / POSIX, BSD. (and tr) +# Hide "\n" from shell by "\fNL" + +decode_arg() { + printf '%s' "$(printf '%s' "$1" | perl -pe 's/#(\d+);/sprintf("%c", $1)/ge; s/[\r\n]/\fNL/g')" +} + +# getopt(s) +while [ $# -ge 1 ]; do + arg="$(printf '%s' "$1" | grep -E '^-+[^-]+$' | tr '[A-Z]' '[a-z]' | tr -d '-')" + case "$arg" in + 'display') shift; options_display="$(decode_arg "$1")";; + 'displayonly') options_displayOnly=true;; + 'keyin') options_keyIn=true;; + 'hideechoback') options_hideEchoBack=true;; + 'mask') shift; options_mask="$(decode_arg "$1")";; + 'limit') shift; options_limit="$(decode_arg "$1")";; + 'casesensitive') options_caseSensitive=true;; + esac + shift +done + +reset_tty() { + if [ -n "$save_tty" ]; then + stty --file=/dev/tty "$save_tty" 2>/dev/null || \ + stty -F /dev/tty "$save_tty" 2>/dev/null || \ + stty -f /dev/tty "$save_tty" || exit $? + fi +} +trap 'reset_tty' EXIT +save_tty="$(stty --file=/dev/tty -g 2>/dev/null || stty -F /dev/tty -g 2>/dev/null || stty -f /dev/tty -g || exit $?)" + +[ -z "$options_display" ] && [ "$options_keyIn" = true ] && \ + [ "$options_hideEchoBack" = true ] && [ -z "$options_mask" ] && silent=true +[ "$options_hideEchoBack" != true ] && [ "$options_keyIn" != true ] && is_cooked=true + +write_tty() { + # if [ "$2" = true ]; then + # printf '%b' "$1" >/dev/tty + # else + # printf '%s' "$1" >/dev/tty + # fi + printf '%s' "$1" | perl -pe 's/\fNL/\r\n/g' >/dev/tty +} + +replace_allchars() { ( + text='' + for i in $(seq 1 ${#1}) + do + text="$text$2" + done + printf '%s' "$text" +) } + +if [ -n "$options_display" ]; then + write_tty "$options_display" +fi +if [ "$options_displayOnly" = true ]; then + printf "'%s'" '' + exit 0 +fi + +if [ "$is_cooked" = true ]; then + stty --file=/dev/tty cooked 2>/dev/null || \ + stty -F /dev/tty cooked 2>/dev/null || \ + stty -f /dev/tty cooked || exit $? +else + stty --file=/dev/tty raw -echo 2>/dev/null || \ + stty -F /dev/tty raw -echo 2>/dev/null || \ + stty -f /dev/tty raw -echo || exit $? +fi + +[ "$options_keyIn" = true ] && req_size=1 + +if [ "$options_keyIn" = true ] && [ -n "$options_limit" ]; then + if [ "$options_caseSensitive" = true ]; then + limit_ptn="$options_limit" + else + # Safe list + # limit_ptn="$(printf '%s' "$options_limit" | sed 's/\([a-z]\)/\L\1\U\1/ig')" + limit_ptn="$(printf '%s' "$options_limit" | perl -pe 's/([a-z])/lc($1) . uc($1)/ige')" + fi +fi + +while : +do + if [ "$is_cooked" != true ]; then + # chunk="$(dd if=/dev/tty bs=1 count=1 2>/dev/null)" + chunk="$(dd if=/dev/tty bs=1 count=1 2>/dev/null | perl -pe 's/[\r\n]/\fNL/g')" + else + IFS= read -r chunk ', + hideEchoBack: false, + mask: '*', + limit: [], + limitMessage: 'Input another, please.$<( [)limit(])>', + defaultInput: '', + trueValue: [], + falseValue: [], + caseSensitive: false, + keepWhitespace: false, + encoding: 'utf8', + bufferSize: 1024, + print: void 0, + history: true, + cd: false, + phContent: void 0, + preCheck: void 0 + /* eslint-enable key-spacing */ + }, + + fdR = 'none', fdW, ttyR, isRawMode = false, + extHostPath, extHostArgs, tempdir, salt = 0, + lastInput = '', inputHistory = [], rawInput, + _DBG_useExt = false, _DBG_checkOptions = false, _DBG_checkMethod = false; + +function getHostArgs(options) { + // Send any text to crazy Windows shell safely. + function encodeArg(arg) { + return arg.replace(/[^\w\u0080-\uFFFF]/g, function(chr) { + return '#' + chr.charCodeAt(0) + ';'; + }); + } + + return extHostArgs.concat((function(conf) { + var args = []; + Object.keys(conf).forEach(function(optionName) { + if (conf[optionName] === 'boolean') { + if (options[optionName]) { args.push('--' + optionName); } + } else if (conf[optionName] === 'string') { + if (options[optionName]) { + args.push('--' + optionName, encodeArg(options[optionName])); + } + } + }); + return args; + })({ + /* eslint-disable key-spacing */ + display: 'string', + displayOnly: 'boolean', + keyIn: 'boolean', + hideEchoBack: 'boolean', + mask: 'string', + limit: 'string', + caseSensitive: 'boolean' + /* eslint-enable key-spacing */ + })); +} + +// piping via files (for Node.js v0.10-) +function _execFileSync(options, execOptions) { + + function getTempfile(name) { + var filepath, suffix = '', fd; + tempdir = tempdir || require('os').tmpdir(); + + while (true) { + filepath = pathUtil.join(tempdir, name + suffix); + try { + fd = fs.openSync(filepath, 'wx'); + } catch (e) { + if (e.code === 'EEXIST') { + suffix++; + continue; + } else { + throw e; + } + } + fs.closeSync(fd); + break; + } + return filepath; + } + + var hostArgs, shellPath, shellArgs, res = {}, exitCode, extMessage, + pathStdout = getTempfile('readline-sync.stdout'), + pathStderr = getTempfile('readline-sync.stderr'), + pathExit = getTempfile('readline-sync.exit'), + pathDone = getTempfile('readline-sync.done'), + crypto = require('crypto'), shasum, decipher, password; + + shasum = crypto.createHash(ALGORITHM_HASH); + shasum.update('' + process.pid + (salt++) + Math.random()); + password = shasum.digest('hex'); + decipher = crypto.createDecipher(ALGORITHM_CIPHER, password); + + hostArgs = getHostArgs(options); + if (IS_WIN) { + shellPath = process.env.ComSpec || 'cmd.exe'; + process.env.Q = '"'; // The quote (") that isn't escaped. + // `()` for ignore space by echo + shellArgs = ['/V:ON', '/S', '/C', + '(%Q%' + shellPath + '%Q% /V:ON /S /C %Q%' + /* ESLint bug? */ // eslint-disable-line no-path-concat + '%Q%' + extHostPath + '%Q%' + + hostArgs.map(function(arg) { return ' %Q%' + arg + '%Q%'; }).join('') + + ' & (echo !ERRORLEVEL!)>%Q%' + pathExit + '%Q%%Q%) 2>%Q%' + pathStderr + '%Q%' + + ' |%Q%' + process.execPath + '%Q% %Q%' + __dirname + '\\encrypt.js%Q%' + + ' %Q%' + ALGORITHM_CIPHER + '%Q% %Q%' + password + '%Q%' + + ' >%Q%' + pathStdout + '%Q%' + + ' & (echo 1)>%Q%' + pathDone + '%Q%']; + } else { + shellPath = '/bin/sh'; + shellArgs = ['-c', + // Use `()`, not `{}` for `-c` (text param) + '("' + extHostPath + '"' + /* ESLint bug? */ // eslint-disable-line no-path-concat + hostArgs.map(function(arg) { return " '" + arg.replace(/'/g, "'\\''") + "'"; }).join('') + + '; echo $?>"' + pathExit + '") 2>"' + pathStderr + '"' + + ' |"' + process.execPath + '" "' + __dirname + '/encrypt.js"' + + ' "' + ALGORITHM_CIPHER + '" "' + password + '"' + + ' >"' + pathStdout + '"' + + '; echo 1 >"' + pathDone + '"']; + } + if (_DBG_checkMethod) { _DBG_checkMethod('_execFileSync', hostArgs); } + try { + childProc.spawn(shellPath, shellArgs, execOptions); + } catch (e) { + res.error = new Error(e.message); + res.error.method = '_execFileSync - spawn'; + res.error.program = shellPath; + res.error.args = shellArgs; + } + + while (fs.readFileSync(pathDone, {encoding: options.encoding}).trim() !== '1') {} // eslint-disable-line no-empty + if ((exitCode = + fs.readFileSync(pathExit, {encoding: options.encoding}).trim()) === '0') { + res.input = + decipher.update(fs.readFileSync(pathStdout, {encoding: 'binary'}), + 'hex', options.encoding) + + decipher.final(options.encoding); + } else { + extMessage = fs.readFileSync(pathStderr, {encoding: options.encoding}).trim(); + res.error = new Error(DEFAULT_ERR_MSG + (extMessage ? '\n' + extMessage : '')); + res.error.method = '_execFileSync'; + res.error.program = shellPath; + res.error.args = shellArgs; + res.error.extMessage = extMessage; + res.error.exitCode = +exitCode; + } + + fs.unlinkSync(pathStdout); + fs.unlinkSync(pathStderr); + fs.unlinkSync(pathExit); + fs.unlinkSync(pathDone); + + return res; +} + +function readlineExt(options) { + var hostArgs, res = {}, extMessage, + execOptions = {env: process.env, encoding: options.encoding}; + + if (!extHostPath) { + if (IS_WIN) { + if (process.env.PSModulePath) { // Windows PowerShell + extHostPath = 'powershell.exe'; + extHostArgs = ['-ExecutionPolicy', 'Bypass', '-File', __dirname + '\\read.ps1']; // eslint-disable-line no-path-concat + } else { // Windows Script Host + extHostPath = 'cscript.exe'; + extHostArgs = ['//nologo', __dirname + '\\read.cs.js']; // eslint-disable-line no-path-concat + } + } else { + extHostPath = '/bin/sh'; + extHostArgs = [__dirname + '/read.sh']; // eslint-disable-line no-path-concat + } + } + if (IS_WIN && !process.env.PSModulePath) { // Windows Script Host + // ScriptPW (Win XP and Server2003) needs TTY stream as STDIN. + // In this case, If STDIN isn't TTY, an error is thrown. + execOptions.stdio = [process.stdin]; + } + + if (childProc.execFileSync) { + hostArgs = getHostArgs(options); + if (_DBG_checkMethod) { _DBG_checkMethod('execFileSync', hostArgs); } + try { + res.input = childProc.execFileSync(extHostPath, hostArgs, execOptions); + } catch (e) { // non-zero exit code + extMessage = e.stderr ? (e.stderr + '').trim() : ''; + res.error = new Error(DEFAULT_ERR_MSG + (extMessage ? '\n' + extMessage : '')); + res.error.method = 'execFileSync'; + res.error.program = extHostPath; + res.error.args = hostArgs; + res.error.extMessage = extMessage; + res.error.exitCode = e.status; + res.error.code = e.code; + res.error.signal = e.signal; + } + } else { + res = _execFileSync(options, execOptions); + } + if (!res.error) { + res.input = res.input.replace(/^\s*'|'\s*$/g, ''); + options.display = ''; + } + + return res; +} + +/* + display: string + displayOnly: boolean + keyIn: boolean + hideEchoBack: boolean + mask: string + limit: string (pattern) + caseSensitive: boolean + keepWhitespace: boolean + encoding, bufferSize, print +*/ +function _readlineSync(options) { + var input = '', displaySave = options.display, + silent = !options.display && + options.keyIn && options.hideEchoBack && !options.mask; + + function tryExt() { + var res = readlineExt(options); + if (res.error) { throw res.error; } + return res.input; + } + + if (_DBG_checkOptions) { _DBG_checkOptions(options); } + + (function() { // open TTY + var fsB, constants, verNum; + + function getFsB() { + if (!fsB) { + fsB = process.binding('fs'); // For raw device path + constants = process.binding('constants'); + } + return fsB; + } + + if (typeof fdR !== 'string') { return; } + fdR = null; + + if (IS_WIN) { + // iojs-v2.3.2+ input stream can't read first line. (#18) + // ** Don't get process.stdin before check! ** + // Fixed v5.1.0 + // Fixed v4.2.4 + // It regressed again in v5.6.0, it is fixed in v6.2.0. + verNum = (function(ver) { // getVerNum + var nums = ver.replace(/^\D+/, '').split('.'); + var verNum = 0; + if ((nums[0] = +nums[0])) { verNum += nums[0] * 10000; } + if ((nums[1] = +nums[1])) { verNum += nums[1] * 100; } + if ((nums[2] = +nums[2])) { verNum += nums[2]; } + return verNum; + })(process.version); + if (!(verNum >= 20302 && verNum < 40204 || verNum >= 50000 && verNum < 50100 || verNum >= 50600 && verNum < 60200) && + process.stdin.isTTY) { + process.stdin.pause(); + fdR = process.stdin.fd; + ttyR = process.stdin._handle; + } else { + try { + // The stream by fs.openSync('\\\\.\\CON', 'r') can't switch to raw mode. + // 'CONIN$' might fail on XP, 2000, 7 (x86). + fdR = getFsB().open('CONIN$', constants.O_RDWR, parseInt('0666', 8)); + ttyR = new TTY(fdR, true); + } catch (e) { /* ignore */ } + } + + if (process.stdout.isTTY) { + fdW = process.stdout.fd; + } else { + try { + fdW = fs.openSync('\\\\.\\CON', 'w'); + } catch (e) { /* ignore */ } + if (typeof fdW !== 'number') { // Retry + try { + fdW = getFsB().open('CONOUT$', constants.O_RDWR, parseInt('0666', 8)); + } catch (e) { /* ignore */ } + } + } + + } else { + if (process.stdin.isTTY) { + process.stdin.pause(); + try { + fdR = fs.openSync('/dev/tty', 'r'); // device file, not process.stdin + ttyR = process.stdin._handle; + } catch (e) { /* ignore */ } + } else { + // Node.js v0.12 read() fails. + try { + fdR = fs.openSync('/dev/tty', 'r'); + ttyR = new TTY(fdR, false); + } catch (e) { /* ignore */ } + } + + if (process.stdout.isTTY) { + fdW = process.stdout.fd; + } else { + try { + fdW = fs.openSync('/dev/tty', 'w'); + } catch (e) { /* ignore */ } + } + } + })(); + + (function() { // try read + var atEol, limit, + isCooked = !options.hideEchoBack && !options.keyIn, + buffer, reqSize, readSize, chunk, line; + rawInput = ''; + + // Node.js v0.10- returns an error if same mode is set. + function setRawMode(mode) { + if (mode === isRawMode) { return true; } + if (ttyR.setRawMode(mode) !== 0) { return false; } + isRawMode = mode; + return true; + } + + if (_DBG_useExt || !ttyR || + typeof fdW !== 'number' && (options.display || !isCooked)) { + input = tryExt(); + return; + } + + if (options.display) { + fs.writeSync(fdW, options.display); + options.display = ''; + } + if (options.displayOnly) { return; } + + if (!setRawMode(!isCooked)) { + input = tryExt(); + return; + } + + reqSize = options.keyIn ? 1 : options.bufferSize; + // Check `allocUnsafe` to make sure of the new API. + buffer = Buffer.allocUnsafe && Buffer.alloc ? Buffer.alloc(reqSize) : new Buffer(reqSize); + + if (options.keyIn && options.limit) { + limit = new RegExp('[^' + options.limit + ']', + 'g' + (options.caseSensitive ? '' : 'i')); + } + + while (true) { + readSize = 0; + try { + readSize = fs.readSync(fdR, buffer, 0, reqSize); + } catch (e) { + if (e.code !== 'EOF') { + setRawMode(false); + input += tryExt(); + return; + } + } + if (readSize > 0) { + chunk = buffer.toString(options.encoding, 0, readSize); + rawInput += chunk; + } else { + chunk = '\n'; + rawInput += String.fromCharCode(0); + } + + if (chunk && typeof (line = (chunk.match(/^(.*?)[\r\n]/) || [])[1]) === 'string') { + chunk = line; + atEol = true; + } + + // other ctrl-chars + // eslint-disable-next-line no-control-regex + if (chunk) { chunk = chunk.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, ''); } + if (chunk && limit) { chunk = chunk.replace(limit, ''); } + + if (chunk) { + if (!isCooked) { + if (!options.hideEchoBack) { + fs.writeSync(fdW, chunk); + } else if (options.mask) { + fs.writeSync(fdW, (new Array(chunk.length + 1)).join(options.mask)); + } + } + input += chunk; + } + + if (!options.keyIn && atEol || + options.keyIn && input.length >= reqSize) { break; } + } + + if (!isCooked && !silent) { fs.writeSync(fdW, '\n'); } + setRawMode(false); + })(); + + if (options.print && !silent) { + options.print(displaySave + (options.displayOnly ? '' : + (options.hideEchoBack ? (new Array(input.length + 1)).join(options.mask) + : input) + '\n'), // must at least write '\n' + options.encoding); + } + + return options.displayOnly ? '' : + (lastInput = options.keepWhitespace || options.keyIn ? input : input.trim()); +} + +function flattenArray(array, validator) { + var flatArray = []; + function _flattenArray(array) { + if (array == null) { + return; + } else if (Array.isArray(array)) { + array.forEach(_flattenArray); + } else if (!validator || validator(array)) { + flatArray.push(array); + } + } + _flattenArray(array); + return flatArray; +} + +function escapePattern(pattern) { + return pattern.replace(/[\x00-\x7f]/g, // eslint-disable-line no-control-regex + function(s) { return '\\x' + ('00' + s.charCodeAt().toString(16)).substr(-2); }); +} + +// margeOptions(options1, options2 ... ) +// margeOptions(true, options1, options2 ... ) +// arg1=true : Start from defaultOptions and pick elements of that. +function margeOptions() { + var optionsList = Array.prototype.slice.call(arguments), + optionNames, fromDefault; + + if (optionsList.length && typeof optionsList[0] === 'boolean') { + fromDefault = optionsList.shift(); + if (fromDefault) { + optionNames = Object.keys(defaultOptions); + optionsList.unshift(defaultOptions); + } + } + + return optionsList.reduce(function(options, optionsPart) { + if (optionsPart == null) { return options; } + + // ======== DEPRECATED ======== + if (optionsPart.hasOwnProperty('noEchoBack') && + !optionsPart.hasOwnProperty('hideEchoBack')) { + optionsPart.hideEchoBack = optionsPart.noEchoBack; + delete optionsPart.noEchoBack; + } + if (optionsPart.hasOwnProperty('noTrim') && + !optionsPart.hasOwnProperty('keepWhitespace')) { + optionsPart.keepWhitespace = optionsPart.noTrim; + delete optionsPart.noTrim; + } + // ======== /DEPRECATED ======== + + if (!fromDefault) { optionNames = Object.keys(optionsPart); } + optionNames.forEach(function(optionName) { + var value; + if (!optionsPart.hasOwnProperty(optionName)) { return; } + value = optionsPart[optionName]; + switch (optionName) { + // _readlineSync <- * * -> defaultOptions + // ================ string + case 'mask': // * * + case 'limitMessage': // * + case 'defaultInput': // * + case 'encoding': // * * + value = value != null ? value + '' : ''; + if (value && optionName !== 'limitMessage') { value = value.replace(/[\r\n]/g, ''); } + options[optionName] = value; + break; + // ================ number(int) + case 'bufferSize': // * * + if (!isNaN(value = parseInt(value, 10)) && typeof value === 'number') { + options[optionName] = value; // limited updating (number is needed) + } + break; + // ================ boolean + case 'displayOnly': // * + case 'keyIn': // * + case 'hideEchoBack': // * * + case 'caseSensitive': // * * + case 'keepWhitespace': // * * + case 'history': // * + case 'cd': // * + options[optionName] = !!value; + break; + // ================ array + case 'limit': // * * to string for readlineExt + case 'trueValue': // * + case 'falseValue': // * + options[optionName] = flattenArray(value, function(value) { + var type = typeof value; + return type === 'string' || type === 'number' || + type === 'function' || value instanceof RegExp; + }).map(function(value) { + return typeof value === 'string' ? value.replace(/[\r\n]/g, '') : value; + }); + break; + // ================ function + case 'print': // * * + case 'phContent': // * + case 'preCheck': // * + options[optionName] = typeof value === 'function' ? value : void 0; + break; + // ================ other + case 'prompt': // * + case 'display': // * + options[optionName] = value != null ? value : ''; + break; + // no default + } + }); + return options; + }, {}); +} + +function isMatched(res, comps, caseSensitive) { + return comps.some(function(comp) { + var type = typeof comp; + return type === 'string' ? + (caseSensitive ? res === comp : res.toLowerCase() === comp.toLowerCase()) : + type === 'number' ? parseFloat(res) === comp : + type === 'function' ? comp(res) : + comp instanceof RegExp ? comp.test(res) : false; + }); +} + +function replaceHomePath(path, expand) { + var homePath = pathUtil.normalize( + IS_WIN ? (process.env.HOMEDRIVE || '') + (process.env.HOMEPATH || '') : + process.env.HOME || '').replace(/[\/\\]+$/, ''); + path = pathUtil.normalize(path); + return expand ? path.replace(/^~(?=\/|\\|$)/, homePath) : + path.replace(new RegExp('^' + escapePattern(homePath) + + '(?=\\/|\\\\|$)', IS_WIN ? 'i' : ''), '~'); +} + +function replacePlaceholder(text, generator) { + var PTN_INNER = '(?:\\(([\\s\\S]*?)\\))?(\\w+|.-.)(?:\\(([\\s\\S]*?)\\))?', + rePlaceholder = new RegExp('(\\$)?(\\$<' + PTN_INNER + '>)', 'g'), + rePlaceholderCompat = new RegExp('(\\$)?(\\$\\{' + PTN_INNER + '\\})', 'g'); + + function getPlaceholderText(s, escape, placeholder, pre, param, post) { + var text; + return escape || typeof (text = generator(param)) !== 'string' ? placeholder : + text ? (pre || '') + text + (post || '') : ''; + } + + return text.replace(rePlaceholder, getPlaceholderText) + .replace(rePlaceholderCompat, getPlaceholderText); +} + +function array2charlist(array, caseSensitive, collectSymbols) { + var values, group = [], groupClass = -1, charCode = 0, symbols = '', suppressed; + function addGroup(groups, group) { + if (group.length > 3) { // ellipsis + groups.push(group[0] + '...' + group[group.length - 1]); + suppressed = true; + } else if (group.length) { + groups = groups.concat(group); + } + return groups; + } + + values = array.reduce( + function(chars, value) { return chars.concat((value + '').split('')); }, []) + .reduce(function(groups, curChar) { + var curGroupClass, curCharCode; + if (!caseSensitive) { curChar = curChar.toLowerCase(); } + curGroupClass = /^\d$/.test(curChar) ? 1 : + /^[A-Z]$/.test(curChar) ? 2 : /^[a-z]$/.test(curChar) ? 3 : 0; + if (collectSymbols && curGroupClass === 0) { + symbols += curChar; + } else { + curCharCode = curChar.charCodeAt(0); + if (curGroupClass && curGroupClass === groupClass && + curCharCode === charCode + 1) { + group.push(curChar); + } else { + groups = addGroup(groups, group); + group = [curChar]; + groupClass = curGroupClass; + } + charCode = curCharCode; + } + return groups; + }, []); + values = addGroup(values, group); // last group + if (symbols) { values.push(symbols); suppressed = true; } + return {values: values, suppressed: suppressed}; +} + +function joinChunks(chunks, suppressed) { + return chunks.join(chunks.length > 2 ? ', ' : suppressed ? ' / ' : '/'); +} + +function getPhContent(param, options) { + var text, values, resCharlist = {}, arg; + if (options.phContent) { + text = options.phContent(param, options); + } + if (typeof text !== 'string') { + switch (param) { + case 'hideEchoBack': + case 'mask': + case 'defaultInput': + case 'caseSensitive': + case 'keepWhitespace': + case 'encoding': + case 'bufferSize': + case 'history': + case 'cd': + text = !options.hasOwnProperty(param) ? '' : + typeof options[param] === 'boolean' ? (options[param] ? 'on' : 'off') : + options[param] + ''; + break; + // case 'prompt': + // case 'query': + // case 'display': + // text = options.hasOwnProperty('displaySrc') ? options.displaySrc + '' : ''; + // break; + case 'limit': + case 'trueValue': + case 'falseValue': + values = options[options.hasOwnProperty(param + 'Src') ? param + 'Src' : param]; + if (options.keyIn) { // suppress + resCharlist = array2charlist(values, options.caseSensitive); + values = resCharlist.values; + } else { + values = values.filter(function(value) { + var type = typeof value; + return type === 'string' || type === 'number'; + }); + } + text = joinChunks(values, resCharlist.suppressed); + break; + case 'limitCount': + case 'limitCountNotZero': + text = options[options.hasOwnProperty('limitSrc') ? + 'limitSrc' : 'limit'].length; + text = text || param !== 'limitCountNotZero' ? text + '' : ''; + break; + case 'lastInput': + text = lastInput; + break; + case 'cwd': + case 'CWD': + case 'cwdHome': + text = process.cwd(); + if (param === 'CWD') { + text = pathUtil.basename(text); + } else if (param === 'cwdHome') { + text = replaceHomePath(text); + } + break; + case 'date': + case 'time': + case 'localeDate': + case 'localeTime': + text = (new Date())['to' + + param.replace(/^./, function(str) { return str.toUpperCase(); }) + + 'String'](); + break; + default: // with arg + if (typeof (arg = (param.match(/^history_m(\d+)$/) || [])[1]) === 'string') { + text = inputHistory[inputHistory.length - arg] || ''; + } + } + } + return text; +} + +function getPhCharlist(param) { + var matches = /^(.)-(.)$/.exec(param), text = '', from, to, code, step; + if (!matches) { return null; } + from = matches[1].charCodeAt(0); + to = matches[2].charCodeAt(0); + step = from < to ? 1 : -1; + for (code = from; code !== to + step; code += step) { text += String.fromCharCode(code); } + return text; +} + +// cmd "arg" " a r g " "" 'a"r"g' "a""rg" "arg +function parseCl(cl) { + var reToken = new RegExp(/(\s*)(?:("|')(.*?)(?:\2|$)|(\S+))/g), matches, + taken = '', args = [], part; + cl = cl.trim(); + while ((matches = reToken.exec(cl))) { + part = matches[3] || matches[4] || ''; + if (matches[1]) { + args.push(taken); + taken = ''; + } + taken += part; + } + if (taken) { args.push(taken); } + return args; +} + +function toBool(res, options) { + return ( + (options.trueValue.length && + isMatched(res, options.trueValue, options.caseSensitive)) ? true : + (options.falseValue.length && + isMatched(res, options.falseValue, options.caseSensitive)) ? false : res); +} + +function getValidLine(options) { + var res, forceNext, limitMessage, + matches, histInput, args, resCheck; + + function _getPhContent(param) { return getPhContent(param, options); } + function addDisplay(text) { options.display += (/[^\r\n]$/.test(options.display) ? '\n' : '') + text; } + + options.limitSrc = options.limit; + options.displaySrc = options.display; + options.limit = ''; // for readlineExt + options.display = replacePlaceholder(options.display + '', _getPhContent); + + while (true) { + res = _readlineSync(options); + forceNext = false; + limitMessage = ''; + + if (options.defaultInput && !res) { res = options.defaultInput; } + + if (options.history) { + if ((matches = /^\s*\!(?:\!|-1)(:p)?\s*$/.exec(res))) { // `!!` `!-1` +`:p` + histInput = inputHistory[0] || ''; + if (matches[1]) { // only display + forceNext = true; + } else { // replace input + res = histInput; + } + // Show it even if it is empty (NL only). + addDisplay(histInput + '\n'); + if (!forceNext) { // Loop may break + options.displayOnly = true; + _readlineSync(options); + options.displayOnly = false; + } + } else if (res && res !== inputHistory[inputHistory.length - 1]) { + inputHistory = [res]; + } + } + + if (!forceNext && options.cd && res) { + args = parseCl(res); + switch (args[0].toLowerCase()) { + case 'cd': + if (args[1]) { + try { + process.chdir(replaceHomePath(args[1], true)); + } catch (e) { + addDisplay(e + ''); + } + } + forceNext = true; + break; + case 'pwd': + addDisplay(process.cwd()); + forceNext = true; + break; + // no default + } + } + + if (!forceNext && options.preCheck) { + resCheck = options.preCheck(res, options); + res = resCheck.res; + if (resCheck.forceNext) { forceNext = true; } // Don't switch to false. + } + + if (!forceNext) { + if (!options.limitSrc.length || + isMatched(res, options.limitSrc, options.caseSensitive)) { break; } + if (options.limitMessage) { + limitMessage = replacePlaceholder(options.limitMessage, _getPhContent); + } + } + + addDisplay((limitMessage ? limitMessage + '\n' : '') + + replacePlaceholder(options.displaySrc + '', _getPhContent)); + } + return toBool(res, options); +} + +// for dev +exports._DBG_set_useExt = function(val) { _DBG_useExt = val; }; +exports._DBG_set_checkOptions = function(val) { _DBG_checkOptions = val; }; +exports._DBG_set_checkMethod = function(val) { _DBG_checkMethod = val; }; +exports._DBG_clearHistory = function() { lastInput = ''; inputHistory = []; }; + +// ------------------------------------ + +exports.setDefaultOptions = function(options) { + defaultOptions = margeOptions(true, options); + return margeOptions(true); // copy +}; + +exports.question = function(query, options) { + /* eslint-disable key-spacing */ + return getValidLine(margeOptions(margeOptions(true, options), { + display: query + })); + /* eslint-enable key-spacing */ +}; + +exports.prompt = function(options) { + var readOptions = margeOptions(true, options); + readOptions.display = readOptions.prompt; + return getValidLine(readOptions); +}; + +exports.keyIn = function(query, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions(margeOptions(true, options), { + display: query, + keyIn: true, + keepWhitespace: true + }); + /* eslint-enable key-spacing */ + + // char list + readOptions.limitSrc = readOptions.limit.filter(function(value) { + var type = typeof value; + return type === 'string' || type === 'number'; + }) + .map(function(text) { return replacePlaceholder(text + '', getPhCharlist); }); + // pattern + readOptions.limit = escapePattern(readOptions.limitSrc.join('')); + + ['trueValue', 'falseValue'].forEach(function(optionName) { + readOptions[optionName] = readOptions[optionName].reduce(function(comps, comp) { + var type = typeof comp; + if (type === 'string' || type === 'number') { + comps = comps.concat((comp + '').split('')); + } else { comps.push(comp); } + return comps; + }, []); + }); + + readOptions.display = replacePlaceholder(readOptions.display + '', + function(param) { return getPhContent(param, readOptions); }); + + return toBool(_readlineSync(readOptions), readOptions); +}; + +// ------------------------------------ + +exports.questionEMail = function(query, options) { + if (query == null) { query = 'Input e-mail address: '; } + /* eslint-disable key-spacing */ + return exports.question(query, margeOptions({ + // -------- default + hideEchoBack: false, + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address + limit: /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, + limitMessage: 'Input valid e-mail address, please.', + trueValue: null, + falseValue: null + }, options, { + // -------- forced + keepWhitespace: false, + cd: false + })); + /* eslint-enable key-spacing */ +}; + +exports.questionNewPassword = function(query, options) { + /* eslint-disable key-spacing */ + var resCharlist, min, max, + readOptions = margeOptions({ + // -------- default + hideEchoBack: true, + mask: '*', + limitMessage: 'It can include: $\n' + + 'And the length must be: $', + trueValue: null, + falseValue: null, + caseSensitive: true + }, options, { + // -------- forced + history: false, + cd: false, + // limit (by charlist etc.), + phContent: function(param) { + return param === 'charlist' ? resCharlist.text : + param === 'length' ? min + '...' + max : null; + } + }), + // added: charlist, min, max, confirmMessage, unmatchMessage + charlist, confirmMessage, unmatchMessage, + limit, limitMessage, res1, res2; + /* eslint-enable key-spacing */ + options = options || {}; + + charlist = replacePlaceholder( + options.charlist ? options.charlist + '' : '$', getPhCharlist); + if (isNaN(min = parseInt(options.min, 10)) || typeof min !== 'number') { min = 12; } + if (isNaN(max = parseInt(options.max, 10)) || typeof max !== 'number') { max = 24; } + limit = new RegExp('^[' + escapePattern(charlist) + + ']{' + min + ',' + max + '}$'); + resCharlist = array2charlist([charlist], readOptions.caseSensitive, true); + resCharlist.text = joinChunks(resCharlist.values, resCharlist.suppressed); + + confirmMessage = options.confirmMessage != null ? options.confirmMessage : + 'Reinput a same one to confirm it: '; + unmatchMessage = options.unmatchMessage != null ? options.unmatchMessage : + 'It differs from first one.' + + ' Hit only the Enter key if you want to retry from first one.'; + + if (query == null) { query = 'Input new password: '; } + + limitMessage = readOptions.limitMessage; + while (!res2) { + readOptions.limit = limit; + readOptions.limitMessage = limitMessage; + res1 = exports.question(query, readOptions); + + readOptions.limit = [res1, '']; + readOptions.limitMessage = unmatchMessage; + res2 = exports.question(confirmMessage, readOptions); + } + + return res1; +}; + +function _questionNum(query, options, parser) { + var validValue; + function getValidValue(value) { + validValue = parser(value); + return !isNaN(validValue) && typeof validValue === 'number'; + } + /* eslint-disable key-spacing */ + exports.question(query, margeOptions({ + // -------- default + limitMessage: 'Input valid number, please.' + }, options, { + // -------- forced + limit: getValidValue, + cd: false + // trueValue, falseValue, caseSensitive, keepWhitespace don't work. + })); + /* eslint-enable key-spacing */ + return validValue; +} +exports.questionInt = function(query, options) { + return _questionNum(query, options, function(value) { return parseInt(value, 10); }); +}; +exports.questionFloat = function(query, options) { + return _questionNum(query, options, parseFloat); +}; + +exports.questionPath = function(query, options) { + /* eslint-disable key-spacing */ + var validPath, error = '', + readOptions = margeOptions({ + // -------- default + hideEchoBack: false, + limitMessage: '$Input valid path, please.' + + '$<( Min:)min>$<( Max:)max>', + history: true, + cd: true + }, options, { + // -------- forced + keepWhitespace: false, + limit: function(value) { + var exists, stat, res; + value = replaceHomePath(value, true); + error = ''; // for validate + // mkdir -p + function mkdirParents(dirPath) { + dirPath.split(/\/|\\/).reduce(function(parents, dir) { + var path = pathUtil.resolve((parents += dir + pathUtil.sep)); + if (!fs.existsSync(path)) { + fs.mkdirSync(path); + } else if (!fs.statSync(path).isDirectory()) { + throw new Error('Non directory already exists: ' + path); + } + return parents; + }, ''); + } + + try { + exists = fs.existsSync(value); + validPath = exists ? fs.realpathSync(value) : pathUtil.resolve(value); + // options.exists default: true, not-bool: no-check + if (!options.hasOwnProperty('exists') && !exists || + typeof options.exists === 'boolean' && options.exists !== exists) { + error = (exists ? 'Already exists' : 'No such file or directory') + + ': ' + validPath; + return false; + } + if (!exists && options.create) { + if (options.isDirectory) { + mkdirParents(validPath); + } else { + mkdirParents(pathUtil.dirname(validPath)); + fs.closeSync(fs.openSync(validPath, 'w')); // touch + } + validPath = fs.realpathSync(validPath); + } + if (exists && (options.min || options.max || + options.isFile || options.isDirectory)) { + stat = fs.statSync(validPath); + // type check first (directory has zero size) + if (options.isFile && !stat.isFile()) { + error = 'Not file: ' + validPath; + return false; + } else if (options.isDirectory && !stat.isDirectory()) { + error = 'Not directory: ' + validPath; + return false; + } else if (options.min && stat.size < +options.min || + options.max && stat.size > +options.max) { + error = 'Size ' + stat.size + ' is out of range: ' + validPath; + return false; + } + } + if (typeof options.validate === 'function' && + (res = options.validate(validPath)) !== true) { + if (typeof res === 'string') { error = res; } + return false; + } + } catch (e) { + error = e + ''; + return false; + } + return true; + }, + // trueValue, falseValue, caseSensitive don't work. + phContent: function(param) { + return param === 'error' ? error : + param !== 'min' && param !== 'max' ? null : + options.hasOwnProperty(param) ? options[param] + '' : ''; + } + }); + // added: exists, create, min, max, isFile, isDirectory, validate + /* eslint-enable key-spacing */ + options = options || {}; + + if (query == null) { query = 'Input path (you can "cd" and "pwd"): '; } + + exports.question(query, readOptions); + return validPath; +}; + +// props: preCheck, args, hRes, limit +function getClHandler(commandHandler, options) { + var clHandler = {}, hIndex = {}; + if (typeof commandHandler === 'object') { + Object.keys(commandHandler).forEach(function(cmd) { + if (typeof commandHandler[cmd] === 'function') { + hIndex[options.caseSensitive ? cmd : cmd.toLowerCase()] = commandHandler[cmd]; + } + }); + clHandler.preCheck = function(res) { + var cmdKey; + clHandler.args = parseCl(res); + cmdKey = clHandler.args[0] || ''; + if (!options.caseSensitive) { cmdKey = cmdKey.toLowerCase(); } + clHandler.hRes = + cmdKey !== '_' && hIndex.hasOwnProperty(cmdKey) ? + hIndex[cmdKey].apply(res, clHandler.args.slice(1)) : + hIndex.hasOwnProperty('_') ? hIndex._.apply(res, clHandler.args) : null; + return {res: res, forceNext: false}; + }; + if (!hIndex.hasOwnProperty('_')) { + clHandler.limit = function() { // It's called after preCheck. + var cmdKey = clHandler.args[0] || ''; + if (!options.caseSensitive) { cmdKey = cmdKey.toLowerCase(); } + return hIndex.hasOwnProperty(cmdKey); + }; + } + } else { + clHandler.preCheck = function(res) { + clHandler.args = parseCl(res); + clHandler.hRes = typeof commandHandler === 'function' ? + commandHandler.apply(res, clHandler.args) : true; // true for break loop + return {res: res, forceNext: false}; + }; + } + return clHandler; +} + +exports.promptCL = function(commandHandler, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions({ + // -------- default + hideEchoBack: false, + limitMessage: 'Requested command is not available.', + caseSensitive: false, + history: true + }, options), + // -------- forced + // trueValue, falseValue, keepWhitespace don't work. + // preCheck, limit (by clHandler) + clHandler = getClHandler(commandHandler, readOptions); + /* eslint-enable key-spacing */ + readOptions.limit = clHandler.limit; + readOptions.preCheck = clHandler.preCheck; + exports.prompt(readOptions); + return clHandler.args; +}; + +exports.promptLoop = function(inputHandler, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions({ + // -------- default + hideEchoBack: false, + trueValue: null, + falseValue: null, + caseSensitive: false, + history: true + }, options); + /* eslint-enable key-spacing */ + while (true) { if (inputHandler(exports.prompt(readOptions))) { break; } } + return; +}; + +exports.promptCLLoop = function(commandHandler, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions({ + // -------- default + hideEchoBack: false, + limitMessage: 'Requested command is not available.', + caseSensitive: false, + history: true + }, options), + // -------- forced + // trueValue, falseValue, keepWhitespace don't work. + // preCheck, limit (by clHandler) + clHandler = getClHandler(commandHandler, readOptions); + /* eslint-enable key-spacing */ + readOptions.limit = clHandler.limit; + readOptions.preCheck = clHandler.preCheck; + while (true) { + exports.prompt(readOptions); + if (clHandler.hRes) { break; } + } + return; +}; + +exports.promptSimShell = function(options) { + /* eslint-disable key-spacing */ + return exports.prompt(margeOptions({ + // -------- default + hideEchoBack: false, + history: true + }, options, { + // -------- forced + prompt: (function() { + return IS_WIN ? + '$>' : + // 'user@host:cwd$ ' + (process.env.USER || '') + + (process.env.HOSTNAME ? + '@' + process.env.HOSTNAME.replace(/\..*$/, '') : '') + + ':$$ '; + })() + })); + /* eslint-enable key-spacing */ +}; + +function _keyInYN(query, options, limit) { + var res; + if (query == null) { query = 'Are you sure? '; } + if ((!options || options.guide !== false) && (query += '')) { + query = query.replace(/\s*:?\s*$/, '') + ' [y/n]: '; + } + /* eslint-disable key-spacing */ + res = exports.keyIn(query, margeOptions(options, { + // -------- forced + hideEchoBack: false, + limit: limit, + trueValue: 'y', + falseValue: 'n', + caseSensitive: false + // mask doesn't work. + })); + // added: guide + /* eslint-enable key-spacing */ + return typeof res === 'boolean' ? res : ''; +} +exports.keyInYN = function(query, options) { return _keyInYN(query, options); }; +exports.keyInYNStrict = function(query, options) { return _keyInYN(query, options, 'yn'); }; + +exports.keyInPause = function(query, options) { + if (query == null) { query = 'Continue...'; } + if ((!options || options.guide !== false) && (query += '')) { + query = query.replace(/\s+$/, '') + ' (Hit any key)'; + } + /* eslint-disable key-spacing */ + exports.keyIn(query, margeOptions({ + // -------- default + limit: null + }, options, { + // -------- forced + hideEchoBack: true, + mask: '' + })); + // added: guide + /* eslint-enable key-spacing */ + return; +}; + +exports.keyInSelect = function(items, query, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions({ + // -------- default + hideEchoBack: false + }, options, { + // -------- forced + trueValue: null, + falseValue: null, + caseSensitive: false, + // limit (by items), + phContent: function(param) { + return param === 'itemsCount' ? items.length + '' : + param === 'firstItem' ? (items[0] + '').trim() : + param === 'lastItem' ? (items[items.length - 1] + '').trim() : null; + } + }), + // added: guide, cancel + keylist = '', key2i = {}, charCode = 49 /* '1' */, display = '\n'; + /* eslint-enable key-spacing */ + if (!Array.isArray(items) || !items.length || items.length > 35) { + throw '`items` must be Array (max length: 35).'; + } + + items.forEach(function(item, i) { + var key = String.fromCharCode(charCode); + keylist += key; + key2i[key] = i; + display += '[' + key + '] ' + (item + '').trim() + '\n'; + charCode = charCode === 57 /* '9' */ ? 97 /* 'a' */ : charCode + 1; + }); + if (!options || options.cancel !== false) { + keylist += '0'; + key2i['0'] = -1; + display += '[0] ' + + (options && options.cancel != null && typeof options.cancel !== 'boolean' ? + (options.cancel + '').trim() : 'CANCEL') + '\n'; + } + readOptions.limit = keylist; + display += '\n'; + + if (query == null) { query = 'Choose one from list: '; } + if ((query += '')) { + if (!options || options.guide !== false) { + query = query.replace(/\s*:?\s*$/, '') + ' [$]: '; + } + display += query; + } + + return key2i[exports.keyIn(display, readOptions).toLowerCase()]; +}; + +exports.getRawInput = function() { return rawInput; }; + +// ======== DEPRECATED ======== +function _setOption(optionName, args) { + var options; + if (args.length) { options = {}; options[optionName] = args[0]; } + return exports.setDefaultOptions(options)[optionName]; +} +exports.setPrint = function() { return _setOption('print', arguments); }; +exports.setPrompt = function() { return _setOption('prompt', arguments); }; +exports.setEncoding = function() { return _setOption('encoding', arguments); }; +exports.setMask = function() { return _setOption('mask', arguments); }; +exports.setBufferSize = function() { return _setOption('bufferSize', arguments); }; diff --git a/arrays/studio/node_modules/readline-sync/package.json b/arrays/studio/node_modules/readline-sync/package.json new file mode 100644 index 0000000000..af188973f5 --- /dev/null +++ b/arrays/studio/node_modules/readline-sync/package.json @@ -0,0 +1,41 @@ +{ + "name": "readline-sync", + "version": "1.4.9", + "title": "readlineSync", + "description": "Synchronous Readline for interactively running to have a conversation with the user via a console(TTY).", + "keywords": [ + "readline", + "synchronous", + "interactive", + "prompt", + "question", + "password", + "cli", + "tty", + "command", + "repl", + "keyboard", + "wait", + "block" + ], + "main": "./lib/readline-sync.js", + "files": [ + "lib/*.@(js|ps1|sh)", + "LICENSE-MIT", + "README-Deprecated.md" + ], + "engines": { + "node": ">= 0.8.0" + }, + "homepage": "https://github.com/anseki/readline-sync", + "repository": { + "type": "git", + "url": "git://github.com/anseki/readline-sync.git" + }, + "bugs": "https://github.com/anseki/readline-sync/issues", + "license": "MIT", + "author": { + "name": "anseki", + "url": "https://github.com/anseki" + } +} diff --git a/arrays/studio/package-lock.json b/arrays/studio/package-lock.json new file mode 100644 index 0000000000..2536e18274 --- /dev/null +++ b/arrays/studio/package-lock.json @@ -0,0 +1,20 @@ +{ + "name": "studio", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "readline-sync": "1.4.9" + } + }, + "node_modules/readline-sync": { + "version": "1.4.9", + "resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.9.tgz", + "integrity": "sha512-mp5h1N39kuKbCRGebLPIKTBOhuDw55GaNg5S+K9TW9uDAS1wIHpGUc2YokdUMZJb8GqS49sWmWEDijaESYh0Hg==", + "engines": { + "node": ">= 0.8.0" + } + } + } +} diff --git a/arrays/studio/string-modification.js b/arrays/studio/string-modification.js index 45991b15fc..d7f5cda68a 100644 --- a/arrays/studio/string-modification.js +++ b/arrays/studio/string-modification.js @@ -3,9 +3,13 @@ let str = "LaunchCode"; //1) Use string methods to remove the first three characters from the string and add them to the end. //Hint - define another variable to hold the new string or reassign the new string to str. +let newStr = str.slice(0,3); //Use a template literal to print the original and modified string in a descriptive phrase. +let phrase = "JavaScript rocks!"; +console.log(phrase[phrase.length - 8]); + //2) Modify your code to accept user input. Query the user to enter the number of letters that will be relocated. //3) Add validation to your code to deal with user inputs that are longer than the word. In such cases, default to moving 3 characters. Also, the template literal should note the error. From e25edc4050b2e83f6ec8fc34691f28e04531f26d Mon Sep 17 00:00:00 2001 From: remi Date: Thu, 27 Jun 2024 14:18:57 -0400 Subject: [PATCH 08/12] For Loop V1 --- loops/exercises/for-Loop-Exercises.js | 91 +++++++++++++++++++++++++-- 1 file changed, 87 insertions(+), 4 deletions(-) diff --git a/loops/exercises/for-Loop-Exercises.js b/loops/exercises/for-Loop-Exercises.js index c659c50852..c2aab962ba 100644 --- a/loops/exercises/for-Loop-Exercises.js +++ b/loops/exercises/for-Loop-Exercises.js @@ -1,24 +1,107 @@ /*Exercise #1: Construct for loops that accomplish the following tasks: a. Print the numbers 0 - 20, one number per line. + for (let i = 0; i <= 20; i++) { + console.log(i); +} b. Print only the ODD values from 3 - 29, one number per line. c. Print the EVEN numbers 12 to -14 in descending order, one number per line. d. Challenge - Print the numbers 50 - 20 in descending order, but only if the numbers are multiples of 3. (Your code should work even if you replace 50 or 20 with other numbers). */ + for (let i = 0; i <= 20; i++) {//<= includes the number + console.log(i); + } +console.log(); + +for (let i = 3; i <30; i++) {//++ IS ASCENDING + if (i % 2=== 1) {//if remainder 2 is odd if remainder is 0 even + console.log(i);//print the value that will be looped + } +} + +console.log(); + +for (let i = 12; i >= -14; i -=2) {//-= is descending and icnriment of 2 + console.log(i); +} + +for (let i = 50; i >=20; i --){//-- is DESCENDDING + if (i % 3 === 0) { + console.log(i); + } +} + +console.log(); /*Exercise #2: Initialize two variables to hold the string “LaunchCode” and the array [1, 5, ‘LC101’, ‘blue’, 42]. +*/ + +let varOne = "LaunchCode"; -Construct ``for`` loops to accomplish the following tasks: +let cuteArray = [1, 5, "LC101", "blue", 42]; + +/*Construct ``for`` loops to accomplish the following tasks: a. Print each element of the array to a new line. - b. Print each character of the string - in reverse order - to a new line. */ + b. Print each character of the string - + in reverse order - + to a new line. */ + + + for (let i = 0; i < cuteArray.length ; i++) {//the array length is the limitation condition + console.log(cuteArray[i]);//print the array index at i the loop information dictates i + } + console.log(); + + + for (let i = varOne.length-1; i >= 0; i--) {//read as undefined so use -1 because was donig 1 extra + console.log(varOne[i]); + } + console.log(); /*Exercise #3:Construct a for loop that sorts the array [2, 3, 13, 18, -5, 38, -10, 11, 0, 104] into two new arrays: - a. One array contains the even numbers, and the other holds the odds. - b. Print the arrays to confirm the results. */ \ No newline at end of file + + a. One array contains the even numbers, + and the other holds the odds. + + b. Print the arrays to confirm the results. */ + + let arrayNumbers = [2, 3, 13, 18, -5, 38, -10, 11, 0, 104]; + + let evenNumberedArray = []; + + let oddNumberedArray = []; + +for (let i = 0; i < arrayNumbers.length; i ++) {//PUT LESS THAN NOT <= or = BECAUSE WILL DO ONE EXTRA AND THATS WRONG + //console.log("index " + i); + //console.log(arrayNumbers[i]); + if (arrayNumbers[i] % 2 === 0) { + //console.log("EVE IN"); + evenNumberedArray.push(arrayNumbers[i]);//TO PUT IN EVEN ARRAY THE ORIGINAL ARRAY INDEX OF EVEN NUMBERS + } else { + oddNumberedArray.push(arrayNumbers[i]);//WHERE TO GO + WHAT TO PUSH + } +} +console.log(evenNumberedArray); +console.log("============================="); +console.log(oddNumberedArray); + + + + + +/* +) + + + //for (let i = 0; i = ""; i++) { + //if (numbArray % 2 === 0) { + //console.log(numbArray); + + */ \ No newline at end of file From d11cbbae00b5e008d470ea309e3da1d583d2d8ad Mon Sep 17 00:00:00 2001 From: remi Date: Thu, 27 Jun 2024 22:28:38 -0400 Subject: [PATCH 09/12] Studio 5 try V1 --- functions/studio/studio-functions.js | 58 ++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/functions/studio/studio-functions.js b/functions/studio/studio-functions.js index 175fc7f439..cc62fb5556 100644 --- a/functions/studio/studio-functions.js +++ b/functions/studio/studio-functions.js @@ -1,5 +1,7 @@ //We want to COMPLETELY reverse an array by flipping the order of the entries AND flipping the order of characters in each element. +const { text } = require("stream/consumers"); + // Part One: Reverse Characters // 1. Define the function as reverseCharacters. Give it one parameter, which will be the string to reverse. @@ -9,6 +11,36 @@ // 5. Use console.log(reverseCharacters(myVariableName)); to call the function and verify that it correctly reverses the characters in the string. // 6. Optional: Use method chaining to reduce the lines of code within the function. + +/*function reverseCharacters(text) { + newText = text.split(""); + newText.reverse(); + newText = newText.join(""); + return newText; +} + +let textSample = "Dorea" +console.log(reverseCharacters(textSample));*/ + +let stringToReverse = "Tank"; + +function reverseCharacters(str) { + let tmpArr = []; + if(typeof str === "string"){ + tmpArr = str.split(""); + tmpArr.reverse(); + str = tmpArr.join(""); + } else if (typeof str === "number") { + str = String(str); + str = reverseCharacters(str); + } + return str; + } + + + //return str.split("").reverse().join(""); + + // Part Two: Reverse Digits // 1. Add an if statement to reverseCharacters to check the typeof the parameter. @@ -17,6 +49,12 @@ // 4. Return the reversed number. // 5. Be sure to print the result returned by the function to verify that your code works for both strings and numbers. Do this before moving on to the next exercise. + + + + + + // Part Three: Complete Reversal - Create a new function with one parameter, which is the array we want to change. The function should: // 1. Define and initialize an empty array. @@ -30,6 +68,26 @@ let arrayTest1 = ['apple', 'potato', 'Capitalized Words']; let arrayTest2 = [123, 8897, 42, 1168, 8675309]; let arrayTest3 = ['hello', 'world', 123, 'orange']; +function reverseAll(arr) { + + let tmpArr = [];//declare array + + console.log(arr);//print parameter + + for(let i = 0; i < arr.length; i++){//iterator i = 0 condition less than length and ++ + tmpArr.push(reverseCharacters(arr[i]);)//pushes whatever in bracket to the array in reverse characters + } + console.log(tmpArr); + return tmpArr; +} + + +reverseAll(arrayTest1); +reverseAll(arrayTest2); +reverseAll(arrayTest3); + + + // Bonus Missions // 1. Have a clear, descriptive name like funPhrase. From 79f26eeb875415c72e438137fabdac26de95015b Mon Sep 17 00:00:00 2001 From: remi Date: Thu, 11 Jul 2024 00:38:28 -0400 Subject: [PATCH 10/12] Complete V1 --- objects-and-math/exercises/ObjectExercises.js | 96 +++++++++++++++++-- 1 file changed, 89 insertions(+), 7 deletions(-) diff --git a/objects-and-math/exercises/ObjectExercises.js b/objects-and-math/exercises/ObjectExercises.js index 9a50cbdecc..9de521c432 100644 --- a/objects-and-math/exercises/ObjectExercises.js +++ b/objects-and-math/exercises/ObjectExercises.js @@ -2,23 +2,105 @@ let superChimpOne = { name: "Chad", species: "Chimpanzee", mass: 9, - age: 6 + age: 6, + astronautID: 2, + move: function () {return Math.floor(Math.random()*11)} }; let salamander = { name: "Lacey", species: "Axolotl Salamander", mass: 0.1, - age: 5 + age: 5, + astronautID: 3, + move: function () {return Math.floor(Math.random()*11)} }; +let fpsCooked = { + name: "Brad", + species: "Chimpanzee", + mass: 11, + age: 6, + astronautID: 5, + move: function () {return Math.floor(Math.random()*11)} +}; + +let pupper = { + name: "Leroy", + species: "Beagle", + mass: 14, + age: 5, + astronautID: 8, + move: function () {return Math.floor(Math.random()*11)} +}; + +let unKnown = { + name: "Almina", + species: "Tardigrade", + mass: 0.0000000001, + age: 1, + astronautID: 10, + move: function () { + return Math.floor(Math.random()*11) + } +}; + + +let crew = [superChimpOne, salamander, fpsCooked, pupper, unKnown]; + +function crewReports(crewMember) {//. notation to call + + console.log(` + ${crewMember.name} is a ${crewMember.species}. + They are ${crewMember.age} years old and ${crewMember.mass} kilograms. + Their ID is ${crewMember.astronautID}.`) +} + +// crew.forEach(crewReports); +//for each item in the crew ARRAY run this function in () +//aka .length for arrays + // --- crew.forEach(crewReports) --- + // go to crew Array [superChimpOne, salamander, fpsCooked, pupper, unKnown] + // run crewReports on each crewMember of crew Array +console.log("........................."); +let crewSteps = 0; +let crewTurnCounter = 0; //must be inside loop or will not return to 0 for next member of crew +let crewTurnsArray = []; + +function fitnessTest(crewArray) { //crew will be the parameter here + + for (let crewMate of crewArray){//loop goes through each 1 member of the array at a time + crewSteps = 0; + crewTurnCounter = 0; //restarts at 0 when the for loop restarts for the next member + while (crewSteps < 20) {//condition for the loop + + crewSteps += crewMate.move(); //adds the move function ammount together and updates the crewsteps of the 1 member + + crewTurnCounter++; //counter iteration keeping track of each 1 member turn on their way to 20 steps + } + crewTurnsArray.push(crewMate.name + " took " + crewTurnCounter + " turns to take 20 steps.");//push the result of hte crewturncounter into the crew turns array lined up with each member + } + // if (crewSteps >= 20) { + // console.log(`${crewMate.name} took ${crewTurnsArray} turns to take 20 steps.`); + // } + return crewTurnsArray;//need to return functions so that the data can be acessed outside of the function +} + +fitnessTest(crew);//use the function fitness test with the crew parameter + +// console.log(crewTurnsArray); + +for (let crewTurnString of crewTurnsArray) {//for loop that goes through each element in the crewturns array and prints the string element + console.log(crewTurnString); + console.log(); +} -// After you have created the other object literals, add the astronautID property to each one. +// X After you have created the other object literals, add the astronautID property to each one. -// Add a move method to each animal object +// X Add a move method to each animal object -// Create an array to hold the animal objects. +// X Create an array to hold the animal objects. -// Print out the relevant information about each animal. +// X Print out the relevant information about each animal. -// Start an animal race! +// Start an animal race! From 0d08ecad506bb0277a93227e601d75d6c83a977f Mon Sep 17 00:00:00 2001 From: remi Date: Tue, 23 Jul 2024 13:45:38 -0400 Subject: [PATCH 11/12] Classwork --- classes/studio/ClassStudio.js | 51 +++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/classes/studio/ClassStudio.js b/classes/studio/ClassStudio.js index c3a6152140..a8eaa983bc 100644 --- a/classes/studio/ClassStudio.js +++ b/classes/studio/ClassStudio.js @@ -1,9 +1,60 @@ //Declare a class called CrewCandidate with a constructor that takes three parameters—name, mass, and scores. Note that scores will be an array of test results. +class CrewCandidate { + constructor(name, mass, scores) { + this.name = name; + this.mass = mass; + this.scores = scores; + } + addScore(newScore) { + this.scores.push(newScore); + } + average() { + let sum = 0; + for (let i = 0; i < this.scores.length; i++) { + sum += this.scores[i]; + } + let roundedAverage = Math.round(sum / this.scores.length * 100)/100 + return roundedAverage; + } + + status() { + if (this.average() >= 90) { + return "accepted"; + } else if (this.average() >= 90) { + return "Reserve"; + } else if (this.average >= 70){ + return "Probationary"; + } else { + return "Rejected"; + } + } +} + +const kondo = new CrewCandidate("Kondo", "100", [95, 98, 90]); + +console.log(kondo); + +const bubbaBear = new CrewCandidate("Bubba Bear", "135", [88, 85, 90]); +bubbaBear.addScore(78); +console.log(bubbaBear); +console.log(bubbaBear.average()); + +const merryMaltese = new CrewCandidate("Merry Maltese", "1.5", [93, 88, 97]); + +console.log(merryMaltese); + +const gladGator = new CrewCandidate("Glad Gator", "225", [75, 78, 62]); + +console.log(gladGator); //Add methods for adding scores, averaging scores and determining candidate status as described in the studio activity. +console.log(`${bubbaBear.name} earned an average test score of ${bubbaBear.average()}% and has a status of ${bubbaBear.status()}.`) +console.log(`${merryMaltese.name} earned an average test score of ${merryMaltese.average()}% and has a status of ${merryMaltese.status()}.`) +console.log(`${gladGator.name} earned an average test score of ${gladGator.average()}% and has a status of ${gladGator.status()}.`) + //Part 4 - Use the methods to boost Glad Gator’s status to Reserve or higher. How many tests will it take to reach Reserve status? How many to reach Accepted? Remember, scores cannot exceed 100%. \ No newline at end of file From ac44e885e424e24aae1208690a153be2527dfc88 Mon Sep 17 00:00:00 2001 From: remi Date: Thu, 25 Jul 2024 18:19:43 -0400 Subject: [PATCH 12/12] myfirstweb --- html/exercises/index.html | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/html/exercises/index.html b/html/exercises/index.html index 80f716a800..952d199243 100644 --- a/html/exercises/index.html +++ b/html/exercises/index.html @@ -8,9 +8,23 @@ +

Why I Love Web Development

+
+
    Web Development helps developers communicate with users.
+
    It is a combined language between art and science that enables expression.
+
    It is an ever evolving system that is integrated into our society and benefits all.
+
+ this page in particular + +

+ My goals for creating a website are multifaceted.
+ Firstly, I aim to showcase the skills that I have acquired through my journey in coding. This platform will serve as a testament to my growth and proficiency in various programming languages and technologies.
+ Secondly, it provides me with an opportunity to be creative, allowing me to experiment with different design elements and functionalities.
+ Lastly, I seek to gain valuable experience in this area, which will not only enhance my technical expertise but also prepare me for future professional endeavors in web development.
+

\ No newline at end of file