I am trying to get the output of a shell command into my node cli app. I have been trying so many things but nothing seems to get me the output.
The command I run has steps like:
$ particle token list
Checking with the cloud...
? Using account ****#****.com
Please enter your password: [hidden]
? Please enter a login code [optional]
__PASSWORD_ONLY__ (active)
token: sometoken here //this is what I and trying to get mainly
I am running it from my app like
const execute = require('child_process').spawnSync;
const child = execute('particle', ["token", "list"], {encoding: 'utf-8'});
if(child.error) {
console.log("ERROR: ",child.error);
}
console.log("stdout: ",child.stdout);
console.log("stderr: ",child.stderr);
console.log("exist code: ",child.status);
When I run it I get
$ node test.js
stdout: ? Using account ****#****.com
Please enter your password: [input is hidden]
stderr: Checking with the cloud...
exist code: 255
I have tried some other ways found by searching but didn't help much. What can I try so that the command would finish after inputting and returns all the outputs? Help would be much appreciated.
PS: It does not have to be spawnSync or any synchronous method, just using it for test purpose.
Related
I am working on a Docker Swarm data visualization tool with a team.
It works as follows:
Our backend is set up in a way that terminal commands can be executed from our code, where these terminal commands have been promisified and the result of this command should be a string of nodeIDs corresponding to the active nodes in my Docker Swarm. This data is then passed to another helper function, however, I am unable to move past the previously explained step due to an unexpected output from my promisified terminal command.
const getNodeIDs = () => {
console.log('in nodeID helper function');
return execProm("docker node ls --format '{{json .ID}}'").then(
(rawNodeIDs) => {
console.log('rawNodeIds: ', rawNodeIDs);
const parsedNodeIDs = parseRawData(rawNodeIDs);
console.log('parsedNodeIDs: ', parsedNodeIDs);
return parsedNodeIDs;
}
);
};
My code fails on line 6 due to the fact that the data being passed to my parseRawData function is not what it is expected. The console log on line 5 above returns as follows:
{
stdout: 'Saved file tree to doc-filelist.js\n' +
'Copied JS to doc-script.js\n' +
'Compiled CSS to doc-style.css\n',
stderr: ''
}
In addition to this being the wrong output, every time I invoke this command, a new file is created in my codebase labeled "docs" with the following three files inside: doc-filelist.js, doc-script.js, doc-style.css. I am working in a team of 4 other engineers, and I seem to be the only person experiencing this behavior. When I attempt to run the terminal command (featured on line 3 in the first block of code) directly in the terminal itself, I receive the expected output of
"odwch32vsynhxbc0ia2nwicag"
which is the nodeID of the single node currently in my Docker Swarm and what I should be receiving when invoking the terminal command from the code.
I've only been able to find one other stack overflow article dealing with the same issue in which that person was told to try running the terminal command
npm uninstall -g docker
which I have done, and this did not fix my issues. I've also looked into making edits to the Docker daemon itself, but am unsure that this is the real root of the issue. Since I am the only person on my team that seems to be encountering this bug, I have reason to believe that this error has something to do with my dev environment. My containers are running on Docker v4.15.0 and I am working on macOS on an M1 chip computer.
Thanks!
What I want to do is if I have a file called test.js I want to be able to run a Discord command, for example !deletefile, and it will delete the test.js file. Is this possible? If not, is it possible to do something similar but be able to edit the file instead of deleting it?
It seems you want to delete a file using a Discord bot.
You can use the built-in Node.js module, fs for this. Its .unlink method will remove a file. I don't think it's a good idea to remove files through a Discord bot, but the following should work:
const fs = require('fs').promises;
const path = require('path');
const { Client } = require('discord.js');
const client = new Client();
client.on('message', async (message) => {
if (message.author.bot || !message.content.startsWith('!deletefile')) return;
try {
// change the path to your file
await fs.unlink(path.join(__dirname, '../logs/1.test'));
message.channel.send('File is deleted. 🎉');
} catch (error) {
console.log(error);
message.channel.send('⚠️ Oops, there was an error. File is not deleted.');
}
});
And yes, you can also edit files in Node.js.
If you want to use your keyboard, you could focus on the file using your arrow keys and then press CMD + Delete (or CTRL, respectively). Doing this, you can also press Enter to start renaming a file.
I suggest looking at keyboard shortcuts in VS Code:
macOS: https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf
windows: https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf
linux: https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf
Vscode is just a text editor, if you press ctr` you can open the terminal and check what shell do you have, if you installed git then you probably have bash which is a linux shell. you can invest a tiny amount of time and learn bash and you can do much more than deleting a file. the command to delete a file is:
rm filename
I have an issue with the VSCode Node.js debugger.
I have the following code (it downloads an image an calculates its hash):
var request = require('request');
var crypto = require('crypto');
request({ uri : 'http://static.wixstatic.com/media/28f6fa_1519eb247c97446098566248a9f86441.jpg',
encoding: null,
timeout: 10000
}, function (err, res, body) {
if (err) {
return res.status(500).send(err);
}
if (res.statusCode !== 200) {
return res.status(500).send(buildResponse(500, "Image download returned status code " + res.statusCode));
}
console.log(crypto.createHmac('sha256', body).digest('hex'));
});
If I run node test.js, it prints the hash of the file perfectly.
If I run it using VSCode debug mode, it does not.
If I set a break point at line 4 (request({...), the debugger hits the break point.
If I set a break point at line 8 (if (err) { ...), the debugger does not hit the break point.
Am I doing something wrong or is this a bug?
$ node -v
v4.6.0
VSCode version: 1.6.1 Recovery Build
Just use the node-inspector it is for me the better way to debug code of backend
here is the link and there are complete guides to start witht that
https://www.npmjs.com/package/node-inspector
By the way is you want to debug some specific file use the node-debug
node-debug my_file_to_debug.js
I hope it help you.
Ungit looks the perfect tool to learn how git works, as it gives a graphical interface to understand what is going on. I want to share this video explanation (very useful to understand how git works even if you are not planning to use ungit).
It has synchronized my local repository perfectly. Unfortunately, when I have typed the bickbucket git url, it has produced the following error:
Ungit tried to run a git command that resulted in an unhandled error. An automatic bug report was sent.
Command (I didn't type it myself, ungit sent it automatically after typing the URL
git -c color.ui=false -c core.quotepath=false -c core.pager=cat -c credential.helper="C:/Documents and Settings/ch/Datos de programa/npm/node_modules/ungit/bin/credentials-helper 0" ls-remote --tags prototype-towunderlist2
Error. The error is probably because there are spaces in C:/Documents and Settings:
Error: Command failed: C:/Documents and Settings/ch/Datos de programa/npm/node_modules/ungit/bin/credentials-helper 0 get: C:/Documents: No such file or directory
fatal: could not read Password for 'https://chelder86#bitbucket.org': No such file or directory
It looks a Windows issue for me, so I have published it in stackoverflow instead the ungit bug report system.
UPDATE 1. I have found out how to get by, but I got another error:
fatal: Authentication failed for 'https://chelder86#bitbucket.org/chelder86/prototype-towunderlist2.git/'
To get by, I did the following. I opened a new cmd (command line). I went into the repository directory. I typed the same command but adding single quotes into the double quotes as follows:
Instead:
"C:/Documents and Settings/ch/Datos de programa/npm/node_modules/ungit/bin/credentials-helper 0"
I typed:
"C:/'Documents and Settings'/ch/'Datos de programa'/npm/node_modules/ungit/bin/credentials-helper 0"
Then, a form appeared in the browser to wrote my username and password. I wrote them, and the new error appeared in the command line (not in the user interface of the browser).
Screenshot:
UPDATE 2: the line where is generated the path "C:/Documents and Settings/ch/Datos de programa/npm/node_modules/ungit/bin/credentials-helper 0" is located in C:\Documents and Settings\ch\Datos de programa\npm\node_modules\ungit\source\git-api.js. It is:
function credentialsOption(socketId) {
var credentialsHelperPath = path.resolve(__dirname, '..', 'bin', 'credentials-helper').replace(/\\/g, '/');
return '-c credential.helper="' + credentialsHelperPath + ' ' + socketId + '" ';
}
I'm not a Javascript expert, so I need some time to find out how to build the correct path...
UPDATE 3: the temporal fix of the code of UPDATE 2 is the following:
[It is a fix, so I wrote it as an answer instead]
The temporal fix of the code of UPDATE 2 is the following:
function credentialsOption(socketId) {
var credentialsHelperPath = path.resolve(__dirname, '..', 'bin', 'credentials-helper').replace(/\\/g, '/');
var botchedFix1 = '-c credential.helper="' + credentialsHelperPath + ' ' + socketId + '" ';
var botchedFix2 = botchedFix1.replace("Documents and Settings","'Documents and Settings'");
botchedFix2 = botchedFix2.replace("Datos de programa","'Datos de programa'");
return botchedFix2;
}
Then, if I click on Fetch Nodes from prototype-towunderlist2 in the user interface of the internet browser (Firefox), I can enter my username and password. Unfortutately, I got a new error:
Command
git -c color.ui=false -c core.quotepath=false -c core.pager=cat -c credential.helper="C:/'Documents and Settings'/ch/'Datos de programa'/npm/node_modules/ungit/bin/credentials-helper 0" ls-remote --tags prototype-towunderlist2
Error
Error: Command failed: fatal: Authentication failed for 'https://chelder86#bitbucket.org/chelder86/prototype-towunderlist2.git/'
However, if you copy and paste the same command in a new cmd (command line), it seems working perfectly. Push is also working.
Feel free to improve my ugly solution!
Are there equivalent to perl -c syntax check for JavaScript from command? Given that I have NodeJS installed?
JSLint is not considered as it is not a real parser. I think YUI compressor is possible but I don't want to install Java on production machines, so I am checking if Node.JS already provided this syntax check mechanism.
If you want to perform a syntax check like that way we do in perl ( another scripting language) you can simply use node -c <js file-name>
e.g. a JS file as test.js has:
let x = 30
if ( x == 30 ) {
console.log("hello");
else {
console.log( "world");
}
now type in node -c test.js
it will show you
test.js:5
else {
^^^^
SyntaxError: Unexpected token else
at startup (bootstrap_node.js:144:11)
at bootstrap_node.js:509:3
Now after fixing the syntax issue as
let x = 30
if ( x == 30 ) {
console.log("hello");
} else {
console.log( "world");
}
check syntax - node -c test.js will show no syntax error!!
Note - we can even use it to check syntax for all files in a dir. - node -c *.js
Try uglify. You can install it via npm.
Edit: The package name has changed. It is uglify-js.
nodejs --help
explains the -p switch: it evaluates the supplied code and prints the results. So using nodejs -p < /path/to/file.js would be a disastrous way to check the validity of node.js code on your server. One possible solution is the one indicated in this SO thread. The one thing not so good about it - the syntax error messages it reports are not terribly helpful. For instance, it tell you something is wrong but without telling you where it is wrong.