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
Related
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:
I've been playing with Raspberry Pi and Node for fun. I thought for a simple experiment what if I grabbed some user input to turn an LED on and off.
const readline = require('readline');
const log = console.log;
const five = require('johnny-five');
const raspi = require('raspi-io');
const board = new five.Board({
io: new raspi(),
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
board.on('ready', function() {
const led = new five.Led('P1-7');
const recursiveAsyncReadLine = function () {
rl.question('Command: ', function (answer) {
switch(answer) {
case 'on':
log('Got it! Your answer was: "', answer, '"');
led.on();
break;
case 'off':
log('Got it! Your answer was: "', answer, '"');
led.stop().off();
break;
default:
}
recursiveAsyncReadLine();
});
};
recursiveAsyncReadLine();
});
It works however I get 2 strange bugs. In the console output below you'll see it prompts for my input... I enter my input, then it repeats my input in a distorted string of text
(see Example 1). Then after my verification message is output (Got it! Your answer was: " on ") I am met with a ReferenceError: on is not defined (Example 2) even though the
LED lit up perfectly.
Command: on
oonn //Example 1
Got it! Your answer was: " on "
Command:
ReferenceError: on is not defined //Example 2
>> off
ooffff
Got it! Your answer was: " off "
Command:
ReferenceError: off is not defined
>> on
oonn
Got it! Your answer was: " on "
Command:
ReferenceError: on is not defined
>> off
ooffff
Got it! Your answer was: " off "
Command:
ReferenceError: off is not defined
>> on
oonn
Got it! Your answer was: " on "
Command:
ReferenceError: on is not defined
>> off
ooffff
Got it! Your answer was: " off "
Command:
ReferenceError: off is not defined
I am thinking this is not so much a Raspberry Pi/Johnny-five thing and just a plain old JavaScript or Node issue.
Any ideas?
Ok retracing my previous statement looks like your issue is probably
led.stop().off();
In examples for Johny-five they show
led.stop();
led.off();
http://johnny-five.io/examples/led/
Good luck, happy hacking :-)
What happens if you reduce to this (works for me)?
const readline = require('readline');
const log = console.log;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const recursiveAsyncReadLine = function () {
rl.question('Command: ', function (answer) {
switch(answer) {
case 'on':
log('Got it! Your answer was: "', answer, '"');
break;
case 'off':
log('Got it! Your answer was: "', answer, '"');
break;
default:
}
recursiveAsyncReadLine();
});
};
recursiveAsyncReadLine();
If that works, that at least tells us it has something to do with the interaction with either raspi-io or johnny-five. Also where does this run, does this code execute on the pi, if so, do you enter the text directly on the pi or is this being entered remotely. If entered remotely what is the platform of the machine you are entering the text on?
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?");
};
So I'm using this example code from the NodeJS docs:
const readline = require('readline');
const rl = readline.createInterface(process.stdin, process.stdout);
console.log("Hello!");
rl.setPrompt('OHAI> ');
rl.prompt();
rl.on('line', (line) => {
switch(line.trim()) {
case 'hello':
console.log('world!');
break;
default:
console.log('Say what? I might have heard `' + line.trim() + '`');
break;
}
rl.prompt();
}).on('close', () => {
console.log('Have a great day!');
process.exit(0);
});
I'm on Windows, running NodeJS 6.0.0. When I run the file, it writes "Hello!", followed by the first "OHAI> ". So far so good. Now I try writing an arbitrary "asd". When I press enter, one of two things happens:
It prints:
asd
Say what? I might have heard 'asd'
OHAI>
It prints
Say what? I might have heard 'asd'
OHAI>
This only happens on the first input line. It seems to be completely random, however if, after I type node test.js, I press enter fast enough, sometimes I get a newline before the first "OHAI> " and it doesn't print my arbitrary input.
Is there something wrong with the example? Is it a bug in NodeJS? Even if it can't be fixed, I'd be relieved to know what causes it, since I've been pulling my hairs out for hours now.
This should solve the issue.
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
I'm still not sure why this happens, but I've found a way around it. It's a bit ugly, but it does the job.
var rl;
function cli() {
const readline = require('readline');
rl = readline.createInterface(process.stdin, process.stdout);
rl.prompt();
rl.on('line', exec_cmd);
rl.on('close', () => {
console.log('And now we part company.');
process.exit(0);
});
}
function fixfunc() {
//get first input
var input = process.stdin.read();
if (input == null)
return;
input = input.toString("utf-8");
//No longer needed, so remove the listener
process.stdin.removeListener('readable', fixfunc);
process.stdin.resume();
//do whatever you want with the input
exec_cmd(input);
//Initialize readline and let it do its job
cli();
}
process.stdin.pause();
process.stdin.on('readable', fixfunc);
process.stdout.write("> Welcome, Commander!\n> ");
What this basically does, is pause stdin, get the first input, manually call the parsing function and then initalize readline and let it do its job.
I am trying to write a program in Haskell that takes in the input as a string of sentences, calls a javascript file with that input, and return the output of that javascript file as the output of the Haskell file. Right now, the output of the javascript file is not printed. It is not clear whether javascript file is called or not.
Here is the script in Haskell:
main :: IO ()
main =
do
putStrLn "Give me the paragraphs \n"
paragraphs <- getLine
output <- readCreateProcess (shell "node try2.js") paragraphs
putStrLn output
Script in Node.js. The desired output is toplines:
var lexrank = require('./lexrank');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Hi', (answer) => {
var originalText = answer;
var topLines = lexrank.summarize(originalText, 5, function (err, toplines, text) {
if (err) {
console.log(err);
}
rl.write(toplines);
// console.log(toplines);
});
rl.close();
});
I am guessing there is some problem with my way of doing stdin. I am new to Node.js
It took me a really long time but following code works:
Haskell File:
import System.Process
main :: IO ()
main =
do
putStrLn "Give me the paragraphs \n"
paragraphs <- getLine
output <- readCreateProcess (shell "node lexrankReceiver.js") (paragraphs ++ "\n")
putStrLn output
NodeJs File:
// Getting this to work took almost a full day. Javascript gets really freaky
// when using it on terminal.
/* Import necessary modules. */
var lexrank = require('./Lexrank/lexrank.js');
const readline = require('readline');
// var Type = require('type-of-is');
// var utf8 = require('utf8');
// Create readline interface, which needs to be closed in the end.
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Set stdin and stdout to be encoded in utf8. Haskell passes string as basic
// 8-bit unsigned integer array. The output also needs to be encoded so that
// Haskell can read them
process.stdin.setEncoding('utf8');
process.stdout.setEncoding('utf8');
// If a string is readable, start reading.
process.stdin.on('readable', () => {
var chunk = process.stdin.read();
if (chunk !== null) {
var originalText = chunk;
var topLines = lexrank.summarize(originalText, 5, function (err, toplines, text) {
if (err) {
console.log(err);
}
// Loop through the result to form a new paragraph consisted of most
// important sentences in ascending order. Had to split the 0 index and
// the rest indices otherwise the first thing in newParagraphs will be
// undefined.
var newParagraphs = (toplines[0])['text'];
for (var i = 1; i < toplines.length; i++) {
newParagraphs += (toplines[i])['text'];
}
console.log(newParagraphs);
});
}
});
// After the output is finished, set end of file.
// TODO: write a handler for end of writing output.
process.stdin.on('end', () => {
process.stdout.write('\n');
});
// It is incredibly important to close readline. Otherwise, input doesn't
// get sent out.
rl.close();
The problem with the Haskell program you have is that paragraphs is not a line of input, just a string, so to fix the issue you can append a newline, something like:
output <- readCreateProcess (shell "node try2.js") $ paragraphs ++ "\n"
To find this issue I tried replacing question with a shim:
rl.question = function(prompt, cb) {
rl.on('line', function(thing) {
console.log(prompt);
cb(thing);
})
}
And that worked, so I knew it was something to do with how question handles stdin. So after this I tried appending a newline and that worked. Which means question requires a 'line' of input, not just any string, unlike on('line'), oddly enough.