process.stdin.on('data',function(data){input_std_in+=data});
What is the correct explanation for the above piece of code. I am new to Node.js and have found many variations of this on the net, but I am still not clear.
The process.stdin is used to read data from commandline (Simple Explaination) For more see here
So below you are waiting for data event of stdin ie you wait for user to type some data in terminal ,you read it and append it to some string.As node js (javascript) is event driven ,it waits for some event to happen get the data from that event and use it further ,like in the script below it appends to already declared variable.
let input_std_in="";
process.stdin.on('data',function(data){
console.log("Data",data.toString())
input_std_in+=data.toString()
});
See working here
Related
What does
process.stdout.connect({})
do and how can I use it?
Tryied googleing it but found nothing.
Tryied options but get error:
TypeError: self._handle.connect is not a function
As the documentation says, process.stdout returns a stream connected to stdout and that stream is of type Socket. Now, if you check the documentation for Socket and look for the connect method you'll find that it initiates a connection on a given socket.
In order to use process.stdout you don't actually need to call connect, you can just write arbitrary strings to the stream which will get echoed in your stdout, e.g.
process.stdout.write("test"); // will print test to the console
But if logging to the console is your intent, it's probably easier to just use the provided console.log() which adds a lot of formatting and other stuff (see this for further info).
In node.js I create child processes like this for example
child_process.spawn('powershell.exe', ['-executionpolicy', 'remotesigned', '-File', 'save_site_login_web.ps1', data.app_catalogue_url, data.ids.join(",")], { windowsHide:true });
const handler = (data) => {
// send data to client
};
watcher_shell.stdout.on('data', handler);
watcher_shell.stderr.on('data', handler);
However, in the child process, it displays a progress bar like this picture (I got this from running it manually from a powershell terminal). The area on top with the light blue background is static and stays on top, while the text in it updates.
However this progress text doesn't get captured in stdout or stderr. How can I capture this stream in node.js?
Thanks
As mklement0 stated, the progress stream is not directly redirectable.
That being said, since Windows 1809+ there is the new pseudo console (ConPTY) API, which basically allows any program to act like the console, thus capturing output that is written directly to the console.
Doing a quick search, there is the node-pty module which supposedly utilizes the ConPTY API on Windows. I haven't tried it but it looks promising (VS Code is using it for its integrated terminal).
Write-Progress output isn't part of PowerShell's system of output streams, so it cannot be captured - neither in-session from PowerShell, nor externally via stdout or stderr.
From the linked about_Redirection help topic:
There is also a Progress stream in PowerShell, but it does not support redirection.
zett42's helpful answer shows a workaround on Windows that doesn't rely on PowerShell's features.
Short 10sec video of what is happening: https://drive.google.com/file/d/1YZccegry36sZIPxTawGjaQ4Sexw5zGpZ/view
I have a CLI app that asks a user for a selection, then returns a response from a mysql database. The CLI app is run in node.js and prompts questions with Inquirer.
However, after returning the table of information, the next prompt overwrites the table data, making it mostly unreadable. It should appear on its own lines beneath the rest of the data, not overlap. The functions that gather and return the data are asynchronous (they must be in order to loop), but I have tried it with just a short list of standard synchronous functions for testing purposes, and the same problem exists. I have tried it with and without console.table, and the prompt still overwrites the response, as a console table or object list.
I have enabled checkwinsize in Bash with
shopt -s checkwinsize
And it still persists.
Is it Bash? Is it a problem with Inquirer?
I was having this issue as well. In my .then method of my prompt I was using switch and case to determine what to console log depending on the users selection. Then at the bottom I had an if statement checking to if they selected 'Finish' if they didn't I called the prompt function again, which I named 'questionUser'.
That's where I was having the issue, calling questionUser again was overriding my console logs.
What I did was I wrapped the questionUser call in a setTimeout like this:
if(data.option !== 'Finish'){
setTimeout(() => {
questionUser();
}, 1000);
}
This worked for me and allowed my console log data to not get deleted.
Hopefully if anyone else is having this issue this helps, I couldn't find an answer to this specific question anywhere.
I have to show progress of node chid_process commands on UI. I am not able to track the progress of commands using any js lib like progress-bar.
How can i show say "git clone" progress on UI so that user knows the status of the process ?
If you mean in general and not for functions you define specifically for this purpose and want to run separately as child process, you really can't unless the child process provides this information itself via for example STDOUT.
And if so, you can only grab this raw output for then having to parse it to find something you could use to indicate progress. This of course, has its own quirks as the output is typically buffered which require you to think through how you parse the buffer(ing).
On top of that you can run into cases where the output format or order changes in the future in such a way that your program no longer can find the key information it needs.
In the case of git, there is really no progress per-se, only stages - which is fine and can act as a form of progress (stage 1 of 4 etc.).
To grab the output you would use something like:
const spawn = require("child_process").spawn;
const child = spawn("git" , ["clone", "https://some.rep"]);
child.stdout.on("data", data => {
// parse data here...
});
...
and the same for stderr. See Node documentation for more details.
Try the farmhand package.
As the description goes, It is an abstration over child_process that makes it easy to run a function in the background, get its progress, result, and cancel if necessary.
Hope this helps!
So far I've only been able to get text and links from what other people on my discord channel type, but I want to be able to save posted images/gifs. is there any way I can do this through the bot or is it impossible? I'm using discord.js.
Images in Discord.js come in the form of MessageAttachments via Message#attachments. By looping through the amount of attachments, we can retrieve the raw file via MessageAttachment#attachment and the file type using MessageAttachment#name. Then, we use node's FileSystem to write the file onto the system. Here's a quick example. This example assumes you already have the message event and the message variable.
const fs = require('fs');
msg.attachments.forEach(a => {
fs.writeFileSync(`./${a.name}`, a.file); // Write the file to the system synchronously.
});
Please note that in a real world scenario you should surround the synchronous function with a try/catch statement, for errors.
Also note that, according to the docs, the attachment can be a stream. I have yet to have this happen in the real world, but if it does it might be worth checking if a is typeof Stream, and then using fs.createWriteStream and piping the file into it.