This question already has answers here:
Using node.js's prompt for user input? [duplicate]
(4 answers)
Closed 1 year ago.
when I use chrome, I can use prompt function like
let name = prompt('What's your name?');
but when I use atom editor which use node.js as a compiler(i'm not sure this is called 'compiler'), the prompt function doesn't work.
I already tried to install 'prompt for node.js' at NPM but it still doesn't work.
Please help me....
Try this:
var prompt = require('prompt');
//
// Start the prompt
//
prompt.start();
//
// Get two properties from the user: username and email
//
prompt.get(['username', 'email'], function (err, result) {
//
// Log the results.
//
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
});
This is the result:
I'm using Visual Studio Code, however, the result's properly the same. For more information, see this: https://www.npmjs.com/package/prompt
Related
I have a Google Assistant app that uses some API's to retrieve and deliver bus arrival times for my local university. The thing is the API returns the arrival times in a string like this:
"2018-51-02T06:51:11"
I try to maniuplate that string with the slice and indexOf functions that exist within javascript to just get the final time portion of the string, the exact code is
finalString = departure.slice(departure.indexOf('T')+1, departure.length);
but at the end of it all it still only prints out and responds with the original string. Offline and local on my machine that code works, but when uploaded to Firebase Functions it no longer works. Any help with this issue?
app.intent("wheres the catabus", (conv, {route}) => {
var routeDetails;
var closest_stop;
var finalString;
return cataAPIService.getRouteDetails(route)
.then((routeData) => {
routeDetails = routeData;
closest_stop = cataAPIService.findClosestStop(routeData, conv.device.location);
return cataAPIService.getStopDetails(closest_stop.StopId)
})
.then((stopData) => {
var departure = cataAPIService.getEstimatedStopDeparture(routeDetails, stopData);
finalString = departure.slice(departure.indexOf('T')+1, departure.length);
conv.ask('The closest stop to you is at ' + closest_stop.Name + '. The next departure is scheduled for ' + finalString);
})
.catch((error) => {
console.log(error);
conv.ask("I can't get that information right now, please try again.");
});
});
I wasn't able to duplicate your problem on Firebase Cloud Functions using node.js 6 and the following code:
var departure="2018-51-02T06:51:11";
var finalString = departure.slice(departure.indexOf('T')+1, departure.length);
console.log('finalstring',finalString);
As expected, it sent the following to the logs:
finalstring 06:51:11
If you show the complete code that is causing the problem, we may be able to help you out.
The behavior you're seeing suggests that the "T" isn't actually in the string.
Otherwise, I typically use code more like this:
var f2 = departure.split('T')[1];
(but only if I know there is actually a T in the datetime)
This question already has answers here:
Capturing javascript console.log? [duplicate]
(2 answers)
Closed 4 years ago.
I have been seeing in some questions on Stack Overflow that there is examples, example code or snippets. Such as the one below:
console.log(1, 2, 3)
By running the code snippet above you'll see something like this:
I am currently working with something in node.js that also requires to fetch the output from console.logs. I find it fascinating that Stack Overflow is able to do this, whilst I don't even have a single clue how they did this.
I would be very thankful if someone could send me a link to where I can read and learn about how to fetch data form the console API.
Cheers,
Richard
P.S. If someone could edit this post to display the image, I'd be very thankful.
Edit
The project that I'm working on is an Electron app. It uses both the node.js process and the Electron BrowserWindow.
It uses a logger that I'm working on wich needs to fetch data from console.log
Some of the use cases might look like this:
console.log('%d is cool', User.firstName)
// => "Jason is cool"
or
console.log('User ID:', User._id)
// => A5FFE
or
console.log('%cUser connected!', 'color: #00FF00')
// => User connected!
// In green text.
You can overwrite window.console.log with your own function to achieve such an effect. For example:
const oldConsoleLog = console.log.bind(console);
console.log = (...params) => {
const textToDisplay = params.map(param =>
typeof param === 'object'
? JSON.stringify(param)
: param
);
document.body.appendChild(document.createElement('div'))
.textContent = textToDisplay;
oldConsoleLog(...params);
};
console.log('foo');
console.log('bar baz');
console.log({ prop: 'value' });
.as-console-wrapper {
height: 60%
}
In nodejs, console.log just formats the data you pass to it and then writes it to process.stdout which is a stream that goes to your commandline window. To intercept that, you can just listen for events on that stream:
process.stdout.on("data", chunk => {
// Do what you wanna do
});
I had a little freetime so I decided to rewrite all my bash scripts in JavaScript (NodeJS - ES6) with child processes. Everything went smoothly until I wanted to automate user input.
Yes, you can do automate the user input. But there is one Problem - you can't determine if the given data event is a feedback or a request for input. At least I can't find a way to do it.
So basically you can do this:
// new Spawn.
let spawn = require('child_process');
// new ufw process.
let ufw = spawn('ufw', ['enable']);
// Use defined input.
ufw.stdin.setEncoding('utf-8');
ufw.stdout.pipe(process.stdout);
ufw.stdin.write('y\n');
// Event Standard Out.
ufw.stdout.on('data', (data) => {
console.log(data.toString('utf8'));
});
// Event Standard Error.
ufw.stderr.on('data', (err) => {
// Logerror.
console.log(err);
});
// When job is finished (with or without error) it ends up here.
ufw.on('close', (code) => {
// Check if there were errors.
if (code !== 0) console.log('Exited with code: ' + code.toString());
// End input stream.
ufw.stdin.end();
});
The above example works totally fine. But there are 2 things giving me an headache:
Will ufw.stdin.write('y\n'); wait until it is needed and what happens if I have multiple inputs? For example 'yes', 'yes', 'no'. Do I have to write 3 lines of stdin.write()?
Isn't the position where I use ufw.stdin.write('y\n'); a little confusing? I thought I need the input after my prompt made a request for input so I decided to change my code that my stdin.write() could run at the right time, makes sense right? However the only way to check when the 'right' time is on the stdout.on('data', callback) event. That makes thinks a little difficult, since I need to know if the prompt is aksing for user input or not...
Here is my code which I think is totally wrong:
// new Spawn.
let spawn = require('child_process');
// new ufw process.
let ufw = spawn('ufw', ['enable']);
// Event Standard Out.
ufw.stdout.on('data', (data) => {
console.log(data.toString('utf8'));
// Use defined input.
ufw.stdin.setEncoding('utf-8');
ufw.stdout.pipe(process.stdout);
ufw.stdin.write('y\n');
});
// Event Standard Error.
ufw.stderr.on('data', (err) => {
// Logerror.
console.log(err);
});
// When job is finished (with or without error) it ends up here.
ufw.on('close', (code) => {
// Check if there were errors.
if (code !== 0) console.log('Exited with code: ' + code.toString());
// End input stream.
ufw.stdin.end();
});
My major misunderstanding is when to use stdin for user input (automated) and where to place it in my code so it will be used at the right time, for example if I have multiple inputs for something like mysql_secure_installation.
So I was wondering if it is possible and it seems not. I posted an issue for node which ended up beeing closed: https://github.com/nodejs/node/issues/16214
I am asking for a way to determine if the current process is waiting for an input.
There isn't one. I think you have wrong expectations about pipe I/O
because that's simply not how it works.
Talking about expectations, check out expect. There is probably a
node.js port if you look around.
I'll close this out because it's not implementable as a feature, and
as a question nodejs/help is the more appropriate place.
So if anyone has the same problem as I had you can simply write multiple lines into stdin and use that as predefined values. Keep in mind that will eventually break the stream if any input is broken or wrong in feature updates:
// new Spawn.
let spawn = require('child_process');
// new msqlsec process.
let msqlsec = spawn('mysql_secure_installation', ['']);
// Arguments as Array.
let inputArgs = ['password', 'n', 'y', 'y', 'y', 'y'];
// Set correct encodings for logging.
msqlsec.stdin.setEncoding('utf-8');
msqlsec.stdout.setEncoding('utf-8');
msqlsec.stderr.setEncoding('utf-8');
// Use defined input and write line for each of them.
for (let a = 0; a < inputArgs.length; a++) {
msqlsec.stdin.write(inputArgs[a] + '\n');
}
// Event Standard Out.
msqlsec.stdout.on('data', (data) => {
console.log(data.toString('utf8'));
});
// Event Standard Error.
msqlsec.stderr.on('data', (err) => {
// Logerror.
console.log(err);
});
// When job is finished (with or without error) it ends up here.
msqlsec.on('close', (code) => {
// Check if there were errors.
if (code !== 0) console.log('Exited with code: ' + code.toString());
// close input to writeable stream.
msqlsec.stdin.end();
});
For the sake of completeness if someone wants to fill the user input manually you can simply start the given process like this:
// new msqlsec process.
let msqlsec = spawn('mysql_secure_installation', [''], { stdio: 'inherit', shell: true });
This question already has answers here:
chrome.storage.local.get and set [duplicate]
(3 answers)
Closed 8 years ago.
I have a chrome extension that is using storage and I can't get the value from the storage with one enter click.
There is a single input field. After the user enters a value and presses enter, the extension should take the value from storage and add the user's input to this value. The first enter press it doesn't work, but if user clicks Enter for second time, then stored value is seen.
I assume that problem is in the ordering of functions, but I can't understand where exactly.
Code in correct order:
var repo, moduleCodes, url;
// Third process
function getStoredUrl() {
chrome.storage.sync.get(function (item) {
url = item.savedUrl;
});
}
// Fourth process
function setVariables() {
repo = document.getElementById("repo").value.toLowerCase();
moduleCodes = {
admin: "EHEALTHADM"
};
}
// Second process
function openGraph() {
getStoredUrl();
setVariables();
if (moduleCodes[repo] !== undefined) {
// ERROR: field "test" doesn't have value url, but should to have
document.getElementById("test").value = url;
//window.open(url + moduleCodes[repo]);
} else {
returnError("Can't find repo " + repo, "repo");
}
}
var enter = 13;
// First process
function inputRepoListener(e) {
"use strict";
if (e.keyCode === enter) {
openGraph();
}
}
The whole code can be seen on gitHub repo: https://github.com/iriiiina/fisheyeGraph
This is a typical race condition, caused by asynchronous method calls.
The call to storage.sync.get is asynchronous, i.e. the normal program flow continues while the storage values are being retrieved. This means that also the assignment of the (still empty) url variable to the element with id test happens before the storage value retrieval has finished.
Solution: Move everything that should happen after the storage value has been retrieved into the callback of storage.sync.get. If, for example, you assign the url like that, it will work.
chrome.storage.sync.get(function (item) {
url = item.savedUrl;
document.getElementById("test").value = url;
});
So you need to restructure your code in order to meet this criteria.
I want to show correct errors to the user if a transaction with a web database (I´m using Phonegap) fails. In the Error-Callback I ask for the error.code value to determine what went wrong.
The Documentations says this about it. However, I have a case where the transaction fails because a unique constraint is violated by inserting a value that already exists.
function saveErrorCB(err){
console.log(err.code + " " + err.message + " ");
}
err.code shows:
1
err.message shows here:
could not execute statement (19 constraint failed)
My point is, I want to know about other codes like "1". The Phonegap documentation doesnt mention it.
I think the Phonegap documentation does (eventually) link to a W3C page which then says...
UNKNOWN_ERR = 0
DATABASE_ERR = 1
VERSION_ERR = 2
TOO_LARGE_ERR = 3
QUOTA_ERR = 4
SYNTAX_ERR = 5
CONSTRAINT_ERR = 6
TIMEOUT_ERR = 7
It seems err.message is more useful - thanks for telling me about it!