I get this bash script from Iterm2 official site.
printf "\e]1337;SetBadgeFormat=%s\a" $(echo "text" | base64)
I tried exec like bellow, there is no error, but failed to set iterm2 Badge
var exec = require('child_process').exec;
exec('printf "\e]1337;SetBadgeFormat=%s\a" $(echo "text" | base64)');
setBadgeFormat.js =>
#!/usr/bin/env node
var rawBadgeFormat = 'test'
var base64BadgeFormat = new Buffer(rawBadgeFormat).toString('base64')
var setBadgeFormatCmd = 'printf "\\e]1337;SetBadgeFormat=' + base64BadgeFormat + '\\a"'
require('child_process').exec(setBadgeFormatCmd, function(error, stdout, stderr) {
if (error) console.log(error);
process.stdout.write(stdout); // this line actually do the trick
process.stderr.write(stderr);
});
Related
Let say I have this command
somecli -s < "/path/to/file.txt"
How can I convert the above command to NodeJS spawn command ? I did something like this, but seems like it didn't pass the input.
spawn('somecli', ['-s', '<', '"/path/to/file.txt"'], { stdio: 'inherit'}).on('error', function (error) {
// something
});
I can use the exec command below and it's working, but I prefer if we can see the live output.
exec('somecli -s < "/path/to/file.txt"', (e, stdout, stderr) => {
// something
})
something like this should help
const { spawn } = require('child_process');
const fs = require('fs');
const writeStream = fs.createWriteStream("/path/to/file.txt");
const shell = spawn('somecli', ['-s']);
shell.stdout.pipe(writeStream);
To pass file input to command ( STDIN redirection )
$ somecli -s < /path/to/file.txt
We can do it something like this
spawn('somecli', ['-s'], {stdio: [fs.openSync('/path/to/file.txt', 'r'), process.stdout, process.stderr]});
To pass command output to file ( STDOUT redirection )
$ somecli -s > /path/to/file.txt
You may follow Ashish answer
let s = spawn('somecli', ['-s])
s.stdout.pipe(fs.createWriteStream('/path/to/file.txt'))
I am trying to execute two windows commands in sequence and get the result of the later one. Something like:
cd ${directory}
sfdx force:source:convert -d outputTmp/ --json
I have browsed and tried a bunch of third-party libraries, like node-cmd. But so far I haven't got any luck yet. As in node-cmd example:
cmd.get(
`cd ${directory}
sfdx force:source:convert -d outputTmp/ --json`,
function(err, data, stderr) {
This works very well on my macOS machine. But on Windows it tends to execute only the first command.
Is there anyway I can resolve this issue? Even some walk around for just cd {directory} + real command can be really helpful
You can try this:
const exec = require('child_process').exec;
exec(`cd dir
sfdx force:source:convert -d outputTmp/ --json`, (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
return;
}
console.log(stdout);
});
or by using && without backticks:
const exec = require('child_process').exec;
exec('cd dir && sfdx force:source:convert -d outputTmp/ --json', (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
return;
}
console.log(stdout);
});
I wan to automate the creation and extracting of keystore.
The problem I'm facing is how to join the commands using the ' | ' symbol or similar solution.
//Original Command
var command='keytool -exportcert -storepass mypass -keypass mypass
-alias myalias -keystore mykey.keystore | openssl sha1 -binary | openssl base64';
//Arguments for the spawn
var keyArgs = [
'-exportcert',
'-storepass','mypass',
'-keypass','mypass',
'-alias','myalias',
'-keystore',"myjey.keystore",
'openssl','sha1',
'-binary',
'openssl','base64',
];
exec('keytool',keyArgs,{cwd:appCreateFolder+"/"+opt.id+"/Certificates"},function(e){
console.log(chalk.cyan('Key created'));
})
From Node.js v6 you can specify a shell option in spawn method which will run command using shell and thus it is possible to chain commands using spawn method.
For example this:
var spawn = require('child_process').spawn;
var child = spawn('ls && ls && ls', {
shell: true
});
child.stderr.on('data', function (data) {
console.error("STDERR:", data.toString());
});
child.stdout.on('data', function (data) {
console.log("STDOUT:", data.toString());
});
child.on('exit', function (exitCode) {
console.log("Child exited with code: " + exitCode);
});
Will trigger an error on node.js version less than 6:
Error: spawn ls && ls && ls ENOENT
But on version 6 and higher it will return expected result:
node app.js
STDOUT: app.js
STDOUT: app.js
app.js
Child exited with code: 0
The | symbol on the command line is called "piping" because it's like piping streams of data together. What you want is to get ahold of the stdin (Standard In) and stdout (Standard Out) streams for the commands you're executing.
For example, this is how you would spawn the echo command and pipe it's output to grep:
var spawn = require('child_process').spawn;
var echo = spawn('echo', ['The quick brown fox\njumped over the lazy dog.']);
var grep = spawn('grep', ['brown']);
echo.stdout.pipe(grep.stdin);
grep.stdout.pipe(process.stdin);
The above example spawns both the "echo" and "grep" commands. It pipes any output from the echo process's stdout stream to the grep process's stdin stream. Finally we pipe the grep process's stdout stream to the parent process's (your node process) stdin stream so you can see the output in your terminal.
The output would be "The quick brown fox" because I put a newline character in the middle and the grep only matched the first line containing "brown".
You could use the exec function to achieve the same result. Just might be harder to maintain in the future, but if all you need is to quickly run a set of piped commands, you can enter the full command line string (including pipe symbols) and pass it to exec.
var exec = require('child_process').exec;
var cmdString = 'grep "The quick brown fox\njumped over the lazy dog." | grep "brown"';
exec(cmdString, (err, stdout, stderr) => {
console.log(stdout);
});
Or instead of passing in the callback function you could just pipe the output to process.stdin if all you care about is seeing the command output.
exec(cmdString).stdout.pipe(process.stdin);
Here's a quick example of what I believe your code should look like using spawn. May require tweaks since it seems specific to what you're doing.
var keyArgs = [
'-exportcert',
'-storepass','mypass',
'-keypass','mypass',
'-alias','myalias',
'-keystore',"myjey.keystore",
'openssl','sha1',
'-binary',
'openssl','base64',
];
var keyOpts = {
cwd: `${appCreateFolder}/${opt.id}/Certificates`
};
var spawn = require('child_process').spawn;
var keytool = spawn('keytool', keyArgs, keyOpts);
var opensslBinary = spawn('openssl', ['sha1', '-binary']);
var opensslBase64 = spawn('openssl', ['base64']);
keytool.stdout.pipe(opensslBinary.stdin);
opensslBinary.stdout.pipe(opensslBase64.stdin);
opensslBase64.stdout.pipe(process.stdin);
opensslBase64.on('close', () => {
console.log(chalk.cyan('Key created.'));
});
Or using exec:
var exec = require('child_process').exec;
var cmdString = 'keytool -exportcert -storepass mypass -keypass mypass -alias myalias -keystore mykey.keystore | openssl sha1 -binary | openssl base64';
var cmdOpts = {
cwd: `${appCreateFolder}/${opt.id}/Certificates`
};
exec(cmdString, cmdOpts, () => {
console.log(chalk.cyan('Key created.'));
});
I have a linux command to create argument value, but I dont know how to convert it in nodejs. This is linux command line:
echo -n '2147483647/s/link127.0.0.1 secret' | \
openssl md5 -binary | openssl base64 | tr +/ -_ | tr -d =
and result when execute it in terminal
_e4Nc3iduzkWRm01TBBNYw
Please tell me how to make it in nodejs without child process.
Any terminal command can be executed in Node.js by using the exec or spawn. In this case, exec will probably be your best bet. Follow the pattern below just replace my command to list the directories in /home/username with whatever command you want:
var exec = require('child_process').exec;
exec("ls /home/username", function (error, stdout, stderr) {
console.log("error: ", error);
console.log("stdout: ", stdout);
console.log("stderr: ", stderr);
});
Done
var mysecretkey = "secret";
var path = "/s/link";
var ip = '127.0.0.1';
var time = '2147483647';
var path = time + path + ip + ' ' + mysecretkey;
var crypto = require('crypto');
var md5sum = crypto.createHash('md5');
var d = md5sum.update(path).digest('base64');
//#echo -n '2147483647/s/link127.0.0.1 secret' | openssl md5 -binary | openssl base64 | tr +/ -_ | tr -d =
var test = d.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
console.log(test);
How to exec continuously? e.g. ls after cd?
I tried
exec = require('child_process').exec;
exec('cd ~/',
function(){
exec('ls'),
function(err, stdout, stderr){
console.log(stdout); // this logs current dir but not ~/'s
}
}
)
exec('cd ~/').exec('ls', function(err, stdout, stderr){
console.log(stdout);
})//this also fails because first exec returns a ChildProcess Object but not itself.
It is not possible to do this because exec and spawn creates a new process. But there is a way to simulate this. You can start a process with exec and execute multiple commands in the same time:
In the command line if you want to execute 3 commands on the same line you would write:
cmd1 & cmd2 & cmd3
So, all 3 commands run in the same process and have access to the context modified by the previous executed commands.
Let's take your example, you want to execute cd ../ and after that to execute dir and to view the previous directory list.
In cmd you shoud write:
cd../ & dir
From node js you can start a process with exec and to tell it to start another node instance that will evaluate an inline script:
var exec = require('child_process').exec;
var script = "var exec = require('child_process').exec;exec('dir',function(e,d,er){console.log(d);});";
script = '"'+script+'"';//enclose the inline script with "" because it contains spaces
var cmd2 = 'node -e '+script;
var cd = exec('cd ../ &'+cmd2,function(err,stdout,strerr)
{
console.log(stdout);//this would work
})
If you just want to change the current directory you should check the documentation about it http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
You can use nodejs promisify and async/await:
const { promisify } = require('util');
const exec = promisify(require('child_process').exec);
export default async function () {
const cpu = await exec('top -bn1');
const disk = await exec('df -h');
const memory = await exec('free -m');
const payload = {
cpu,
disk,
memory,
};
return payload
}
If you want to use cd first, better use process.chdir('~/'). Then single exec() will do the job.
You can call exec with cwd param like so:
exec('ls -a', {
cwd: '/Users/user'
}, (err, stdout) => {
if (err) {
console.log(err);
} else {
console.log(stdout);
}
})
But beware, cwd doesn't understand '~'. You can use process.env.HOME instead.