NodeJS "readline" module not outputting prompt - javascript

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:

Related

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
}
}
});

Taking simple shell input with 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?");
};

How to read specific data from an uploaded txt file on node js

I need a client to upload a text file. Then I want to parse the text file such that only lines with the word "object" in it is the only thing left in the text file. I have successfully coded the uploading part. But need help coding how to parse out the lines with "object" not in it. My node js code is below.
You can use the ReadLine API that's part of Node Core to iterate through the file line-by-line. You can use string.includes() to determine if your line contains the phrase you're looking for.
var readline = require('readline');
var fs = require('fs');
function filterFile(phrase, input) {
return Promise((resolve, reject) => {
var lines = [];
let rl = readline.createInterface({
input: input
});
rl.on('line', (line) => {
if (line.includes(phrase, 0))
lines.push(line);
});
rl.on('close', () => {
let filteredLines = Buffer.from(lines);
return resolve(fs.createReadStream(filteredLines));
});
rl.on('error', (err) => {
return reject(err);
});
});
}
Edit for Filtered Output Write Stream Example
We can take the resulting stream returned by filterFile() and pipe its contents into a new file like so
var saveDest = './filteredLines.txt');
filterFile('object', inputStream)
.then((filteredStream) => {
let ws = fs.createWriteStream(saveDest);
filteredStream.once('error', (err) => {
return Promise.reject(err);
});
filteredStream.once('end', () => {
console.log(`Filtered File has been created at ${saveDest}`);
return Promise.resolve();
});
filteredStream.pipe(ws);
});
Step : 1
Divide the line using --
var x='i am object\ni m object';
var arr = x.split('\n');
Step : 2
For each line, test with object regexp
var reg = /object/g
if(reg.test(<eachline>)){
// write new line
}else{
// do nothing
}

node.js display virtual hosts and current git branch async issue

Ok, i am just starting to learn node.js and i am having a little difficulty getting a good grasp on the async nature of it and when/how to use callbacks to get data passed along like i need it.
The concept of what i am trying to build is this. I have a small node.js app that uses the FS package - defined as var fs = require("fs"). The app is responding to localhost:4000 right now. When i hit that url, the app will use fs.readdir() to get all of the virtual host files in the directory that i pass to readdir().
Next, the app loops through those files and parses each one line by line and word by word (quick and dirty for now). I am using fs.readFile() to read the file and then literally doing lines = data.toString().split("\n") and then var words = lines[l].split(" ") to get to the data in the file i need. Each virtual host file looks something like this:
<VirtualHost *:80>
ServerName some-site.local
DocumentRoot "/path/to/the/docroot"
<Directory "/path/to/the/docroot">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
</Directory>
ErrorLog "logs/some-site.local-error_log"
</VirtualHost>
Here is my main.js file (routes file):
var express = require("express"),
router = express.Router(),
async = require("async"),
directoryReader = require(__dirname + "/../lib/directoryReader");
fileReader = require(__dirname + "/../lib/fileReader");
router.get("/", function(req, res) {
var response = [];
directoryReader.read(function(files) {
async.each(files, function(file, callback) {
fileReader.read(file, function(data) {
if (data.length > 0) {
response.push(data);
}
callback();
});
}, function(err){
if (err) throw err;
res.json(response);
});
});
});
module.exports = router;
My directoryReader.js file:
var fs = require("fs"),
fileReader = require(__dirname + "/../lib/fileReader");
var directoryReader = {
read: function(callback) {
var self = this;
fs.readdir("/etc/apache2/sites-available", function (err, files) {
if (err) throw err;
var output = [];
for(f in files) {
output.push(files[f]);
}
callback(output);
});
}
};
module.exports = directoryReader;
And my fileReader.js file:
var fs = require("fs");
var fileReader = {
read: function(file, callback) {
fs.readFile("/etc/apache2/sites-available/" + file, { encoding: "utf8" }, function (err, data) {
if (err) throw err;
var vHostStats = ["servername", "documentroot", "errorlog"],
lines = data.toString().split("\n"),
output = [];
for(l in lines) {
var words = lines[l].split(" ");
for(w in words) {
if (words[w].toLowerCase() == "<virtualhost") {
var site = {
"servername" : "",
"documentroot" : "",
"errorlog" : "",
"gitbranch" : ""
}
w++;
}
if (vHostStats.indexOf(words[w].toLowerCase()) !== -1) {
var key = words[w].toLowerCase();
w++;
site[key] = words[w];
}
if (words[w].toLowerCase() == "</virtualhost>" && site.documentroot != "") {
w++;
output.push(site);
var cmd = "cd " + site["documentroot"] + " && git rev-parse --abbrev-ref HEAD";
var branch = ...; // get Git branch based on the above command
site["gitbranch"] = branch;
}
}
}
callback(output);
});
}
};
module.exports = fileReader;
All of this code will spit out json. This all works fine, expect for one part. The line in the fileReader.js file:
var branch = ...; // get Git branch based on the above command
I am trying to get this code to run a shell command and get the Git branch based on the document root directory. I then want to take the branch returned and add the value to the gitbranch proptery of the current site object during the loop. Hope this makes sense. I know there are probably questions on SO that cover something similar to this and i have looked at many of them. I fear i am just not educated enough in node.js yet to apply the answers to those SO questions to my particular use case.
Please let me know if there's anything i can add that can help anyoe answer this question. I should note that this app is for personal uses only, so the solution really just has to work, not be super elegant.
UPDATE: (5/1/2015)
Probably not the best solution but i got what i wanted by using the new execSync added to v0.12.x
if (words[w].toLowerCase() == "</virtualhost>" && site.documentroot != "") {
var cmd = "cd " + site["documentroot"] + " && git rev-parse --abbrev-ref HEAD";
var branch = sh(cmd, { encoding: "utf8" });
site["gitbranch"] = branch.toString().trim();
w++;
output.push(site);
}

process.stdout.write() not working in Node.js readline CLI program

I am using the readline module to create a command line interface (CLI) for an application in Node.js.
The problem is that I can not scroll up to view the past commands as I usually can in Terminal. My CLI is just a fixed window and if I print too much out to the screen, I lose information at the top and there is no way to scroll up to see it.
(I am running my program on Mac OSX Mavericks)
Thanks in advance.
Code Snippet:
var readline = require('readline');
var Cli = function () {
this.txtI = process.stdin;
this.txtO = process.stdout;
process.stdout.write('CLI initialized.');
this.rl = readline.createInterface({input: this.txtI, output: this.txtO });
this.rl.setPrompt('>>>');
this.rl.prompt();
this.rl.on('line', function(line) {
var input = line.toString().trim();
if (input) {
this.txtO.write('cmd: ' + input);
}
this.rl.prompt();
}.bind(this)).on('close', function() {
this.txtO.write('Have a great day!');
process.exit(0);
}.bind(this));
};
new Cli();
Save this file as snippet.js and run
node snippet.js
in terminal.
It probably is working, just readline is overwriting your line. Try outputting multiple lines:
process.stdout.write("1\n2\n3\n4\n5");
Readline is quite an awesome module. History is already there. As is the possibility to add completion. Try the snippet below.
var readline = require('readline');
function createCLI(opt) {
var rl = readline.createInterface({
input : opt.input,
output : opt.output,
terminal : opt.terminal || true,
completer : opt.completer ||
function asyncCompleter(linePartial, callback){
var completion = linePartial.split(/[ ]+/);
callback(null, [completion, linePartial]);
}
});
rl.on('line', function(line) {
if( !line.trim() ){ this.prompt(); }
else { this.write(line); }
}).on('close', function() {
this.output.write('\n Have a great day!');
process.exit(0);
}).setPrompt(' > ');
rl.output.write(' CLI initialized\n');
return rl;
}
var cli = createCLI({
input : process.stdin,
output : process.stdout
});
cli.prompt();

Categories