Taking simple shell input with javascript - javascript

I'm trying to take simple input from a linux shell when a javascript program is run. I've tried using readline() and prompt() but both of those throw Reference Error: readline() is not defined or prompt() is not defined.
//Decode Bluetooth Packets
var advlib = require('advlib');
console.log("What data to process - If you respond N than what is written inline will be decoded");
var input = require();
if (input != "N") {
var rawHexPacket = input
var processedpacket = advlib.ble.process(rawHexPacket);
console.log(JSON.stringify(processedpacket,null, " "));
}
else {
//Put in raw data here!
var rawHexPacket = 'dfasdfasdfasd4654df3asd3fa3s5d4f65a4sdf64asdf';
var processedpacket = advlib.ble.process(rawHexPacket);
console.log(JSON.stringify(processedpacket,null, " "));
}
So what is a simple way to get javascript input through a linux shell?

I used the link posted and turned it into this (which works):
var advlib = require('advlib');
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
try {
rl.question("What data to process - If you respond N then what is written inline will be decoded. ", function(answer) {
console.log("You said: ",answer);
if (answer != "N") {
var rawHexPacket = answer
var processedpacket = advlib.ble.process(rawHexPacket);
console.log(JSON.stringify(processedpacket,null, " "));
}
else {
//Put in raw data here!
var rawHexPacket = '';
var processedpacket = advlib.ble.process(rawHexPacket);
console.log(JSON.stringify(processedpacket,null, " "));
}
});
}
catch(err) {
console.log("Somthing went wrong - was your input valid?");
};

Related

How to run a JavaScript solution from HackerRank on Idea / WebStorm IDE?

Say you want to run / debug a HackerRank solution locally on your WebStorm / IntelliJ Idea IDE for for macOS before submitting it. What are the needed steps, considering node.js is already installed in your machine?
Sample Hello.js file as below:
const fs = require('fs');
function processData(input) {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
var i, result = "";
for (i = 0; i < parseInt(input); i++) {
result += 'Hello - ' + i + '\n';
}
ws.write(result + "\n");
ws.end();
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
On macOS Mojave the steps are:
On Preferences > Keymap, add a keyboard shortcut Ctrl+D to run the Other > Send EOF action; beware this may remove other actions associated to this shortcut, such as "Debug" (credits to this answer)
Add the Hello.js file to your project and open it in the editor
Enter Modify Run Configuration... dialog (Cmd+Shift+A`, type "modify ..." and select it)
make sure Node interpreter:, Working directory: and JavaScript file: are properly set
(if the solution writes output to a file) Set also the Environment variables: to OUTPUT_PATH=./hello.txt or as desired
Save it
Run the configuration. In the terminal pane that opens:
provide the needed input; e.g. 4, then Enter
press Ctrl+D to fire the "end" event
check the generated file hello.txt
You may want to use console.log() to help debugging; make sure it's commented out before submitting your solution back to HackerRank.
Run Configuration:
Run Tool Window:
Try this works on windows, you can run it using node here end event gets triggered when you hit ctrl+D just like hackerrank or Mac os
'use strict';
const { METHODS } = require('http');
const readline = require('readline')
process.stdin.resume();
process.stdin.setEncoding('utf-8');
readline.emitKeypressEvents(process.stdin);
let inputString = '';
let currentLine = 0;
process.stdin.setRawMode(false)
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('keypress', (str, key) => {
if (key && key.ctrl && key.name == 'd'){
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
})
main();
}
});
function readLine() {
return inputString[currentLine++];
}
function method() {
}
function main() {
const n = parseInt(readLine().trim());
const arr = readLine().replace(/\s+$/g, '').split(' ').map(qTemp =>parseInt(qTemp,10))
method();
}

How to find condition of code in file using readline in nodejs?

I tried to read line by line in file using node js.but I have doubt how to get only condition content (if,for) using node js.
data.js
const fs = require('fs')
const path = require("path");
const file_path = path.resolve('./sample')
const check_console = require('./tests_helper')
check_console.files_paths(file_path).then(result =>console.log(result))
.catch(error =>console.log(error))
file.js
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream(files[i])
});
lineReader.on('line', function (line) {
console.log("Line of Code "+line)
});
I got output
Line of Code console.log('hai')
Line of Code
Line of Code console.log('hai')
Line of Code
Line of Code if(10 == 10)
Line of Code {
Line of Code
Line of Code }
but I want Output
Line of Code if(10 == 10)
Line of Code {
Line of Code
Line of Code }
You can use "string".includes("substring"); method to check if that substring exists or not.
I have prepared a quick logic for your problem. line.includes("if") will check if a substring exists and some other condition check I have given to maintain the curly braces.
const fs = require('fs');
const readline = require('readline');
const r1 = readline.createInterface({
input: require('fs').createReadStream(__dirname + '/test.js')
});
found = false;
curlbrace = 0;
r1.on('line', function (line) {
if (line.includes("if")) {
found = true; //setting flag true if found search string
}
if (found && line.includes("{")) {
curlbrace++; //incrementing if breace is started
}
if (found && line.includes("}")) {
curlbrace--; //decrementing if brace is ended
}
if (found && curlbrace >= 0) {
console.log(line); //console the searched result
if (curlbrace == 0) {
found = false; //setting false to prevent it to show other contents
}
}
});

NodeJS "readline" module not outputting prompt

Using NodeJS, I was trying to make a 'note' manager just for fun, but when I tried to use readline.question() to get the user's input on what they would like to do(i.e create a new note, delete a note), the prompt wouldn't be displayed. Any suggestions on how I could fix this issue?
Link To Project
`
fileDatabase = [];
var reply;
var FileName;
var FileContent;
var readline = require('readline');
var async = require('async');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
class NewFile {
constructor(fileName,fileContent){
this.fileName = fileName
this.fileContent = fileContent
}
};
console.log("Hello! Welcome to your file management system.")
async.whilst(
function(){
return reply != "5";
},
function(callback){
rl.question("Press a number:\n1: Create a new file.\n2: View a file.\n3: Add to a file.\n4: Delete a file.\n5: Exit this program.", function(answer) {
var reply = answer
console.log(reply)
rl.close();
});
if (reply === "1") {
rl.question("What would you like to name this file?", function(answer){
var FileName = answer
rl.close()
});
rl.question("Write onto your file. You will be able to edit it later.", function(answer){
var FileContent = answer
rl.close()
});
}
setTimeout(callback, 1000);
},
function(err) {
console.err("we encountered an error", err);
}
)
`
As you are only using an online editor. (At least I am trying to solve your problem of prompting issue.)
I would suggest https://www.katacoda.com/courses/nodejs/playground
Copy your code into app.js file.
You will have the Terminal tab. Please install dependencies first.
npm install -g asynch
npm install -g readline
By which, you will have node_modules folder under the tree.
And click on node app.js link left side highlighted by black color.
Couple of things you should take care about your code:
Please try to assign some default value of reply maybe you can do as var reply = 0
Wrap the list code to the condition if reply = 0.
if (reply === "1") this condition will strictly check with string. use instead if(reply == 1).
And modify your code as per your requirement to fall into next question.
Below is modified code:
fileDatabase = [];
var reply = 0;
var FileName;
var FileContent;
var readline = require('readline');
var async = require('async');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
class NewFile {
constructor(fileName, fileContent) {
this.fileName = fileName;
this.fileContent = fileContent;
}
}
console.log('Hello! Welcome to your file management system.');
async.whilst(
function() {
return reply != '5';
},
function(callback) {
if (reply === 0) {
rl.question(
'Press a number:\n1: Create a new file.\n2: View a file.\n3: Add to a file.\n4: Delete a file.\n5: Exit this program.\n',
function(answer) {
reply = answer;
rl.close();
}
);
}
if (reply == 1) {
rl.question('What would you like to name this file?\n', function(answer) {
var FileName = answer;
rl.close();
});
rl.question(
'Write onto your file. You will be able to edit it later.\n',
function(answer) {
var FileContent = answer;
rl.close();
}
);
}
setTimeout(callback, 1000);
},
function(err) {
console.err('we encountered an error', err);
}
);
For your reference:

Node JS not able to trigger end usinf stdin

I am using NodeJS version v6.9.4. I am trying to execute the below sample code. It continuously but not ending the program. Can anyone help me solve my problem.
var stdin = process.stdin,
stdout = process.stdout,
inputChunks = [];
#stdin.resume();
stdin.setEncoding('ascii');
stdin.on('data', function (chunk) {
inputChunks.push(chunk);
});
stdin.on('end', function () {
var inputJSON = inputChunks.join(),
parsedData = JSON.parse(inputJSON),
outputJSON = JSON.stringify(parsedData, null, ' ');
stdout.write(outputJSON);
stdout.write('\n');
});

I can't read strings written by the user

I am not able to read characters, strings or numbers. I'm starting to learn js and maybe it's an easy question but I cant answer it by myself. The code I'm using is:
var main = function()
{
"use strict";
var stdout = require("system").stdout;
var stdin = require("system").stdin;
stdout.write( "What is your name? " );
var name = stdin.readLine();
stdout.writeLine( "Hello, " + name );
}();
Thanks for your help and sorry if this question is quite silly.
You need to read the doc on how to use readline in Node --https://nodejs.org/api/readline.html#readline_readline:
var main = function()
{
"use strict";
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("What is your name? ", function(answer) {
console.log("Hello ", answer);
rl.close();
});
}();
Vanilla Javascript doesn't support "read strings". However, if you have an html document, you could grab the input from a text box:
document.getElementById('textbox_id').value

Categories