How to use the execSync function from child_process

Find comprehensive JavaScript child_process.execSync code examples handpicked from public code repositorys.

child_process.execSync is a Node.js method that executes a command synchronously and returns the result.

44
45
46
47
48
49
50
51
52
53
console.log(`Prepare theme ${data.color} ${data.variant}...`);
fs.mkdirSync(data.outPath, { recursive: true });
fs.mkdirSync(`${data.outPath}/assets`, { recursive: true });

// Compile sass
execSync(`sass ${data.srcSass} ${data.outCss} --no-source-map`);

// Copy thumbnail
const thumbnailFilePath = `${SRC_PATH}/screenshots/thumbnail-${data.variant}.png`;
execSync(`cp ${thumbnailFilePath} ${data.outPath}/thumbnail.png`);
fork icon118
star icon138
watch icon27

+ 11 other calls in file

31
32
33
34
35
36
37
38
39
40
  return lines.join('\n')
}

module.exports = async function lint({ args = {}, pluginOptions = {} } = {}) {
  if (args.options) {
    execSync('stylelint --help', { stdio: 'inherit' })
    return
  }

  const cwd = process.cwd()
fork icon300
star icon0
watch icon65

How does child_process.execSync work?

child_process.execSync is a synchronous function in Node.js that executes a command in a shell and returns the output of the command as a string. It blocks the main thread until the command is executed and completed. If the command execution results in a non-zero exit code, an error is thrown.

314
315
316
317
318
319
320
321
322
323
customName = customName || pkg.name.split('.').pop();
console.log('Install adapter...');
const startFile = 'node_modules/' + appName + '.js-controller/' + appName + '.js';
// make first install
if (debug) {
    child_process.execSync('node ' + startFile + ' add ' + customName + ' --enabled false', {
        cwd:   rootDir + 'tmp',
        stdio: [0, 1, 2]
    });
    checkIsAdapterInstalled(function (error) {
fork icon48
star icon117
watch icon29

+ 3 other calls in file

6
7
8
9
10
11
12
13
14
15

const path = require('path');
const fs = require('fs');
const childProcess = require('child_process');
const exec = childProcess.exec;
const execSync = childProcess.execSync;
const buildStyle = require('./buildStyle');
const mkdirp = require('mkdirp');

function getDirectories(srcpath) {
fork icon45
star icon0
watch icon18

Ai Example

1
2
3
4
5
6
7
8
const { execSync } = require("child_process");

try {
  const output = execSync("ls");
  console.log(output.toString());
} catch (error) {
  console.error(error);
}

In this example, we import the execSync method from the child_process module and use it to execute the ls command. The execSync method blocks the execution of the program until the command completes and returns the output as a buffer, which we convert to a string and log to the console. Any errors that occur during the execution of the command are thrown as exceptions.

178
179
180
181
182
183
184
185
186
187
  ' ', salt.toString(),
  ' false')

console.log(`Creating deposit transaction by executing smartnode: ${cmd}`)

const cmdOutput = execSync(cmd)
const encodedSignedDepositTx = `0x${cmdOutput.toString().trim()}`
// console.log(`Got tx: ${encodedSignedDepositTx}`)
console.log(`Got deposit transaction data from smartnode`)
return encodedSignedDepositTx
fork icon20
star icon102
watch icon2

68
69
70
71
72
73
74
75
76
77
78
  );
};


try {
  version = require('../package.json').version;
  gitCommit = childProcess.execSync('git rev-parse --short=8 HEAD').toString().replace(/\n/g, '');
  repoUrl = require('../package.json').repository.url;
  if (repoUrl.endsWith('/')) {
    repoUrl = repoUrl.slice(0, -1);
  }
fork icon9
star icon163
watch icon5

118
119
120
121
122
123
124
125
126
127
128
129
// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {


  if (mode === "development") {
    const { execSync } = require("child_process");
    const shell = (cmd) => execSync(cmd, {encoding: "utf8"}).trim();


    try {
      const branch = shell("git branch --show-current");
      const version = shell("git describe --always --long --tags");
fork icon5
star icon7
watch icon7

1
2
3
4
5
6
7
8
9
10
11
const child_process = require("child_process");
const axios = require("axios");
const path = require("path");
const fs = require("fs");


// const ret = child_process.execSync(
//   `npm -registry "https://registry.npmjs.org/"  search --prefer-online --no-description --json "cn-fontsource-"`,
//   { stdio: "pipe", encoding: "utf8" }
// );

fork icon2
star icon4
watch icon1

+ 2 other calls in file

283
284
285
286
287
288
289
290
291
292
/**
 * Builds Blockly as a JS program, by running tsc on all the files in
 * the core directory.
 */
function buildJavaScript(done) {
  execSync(
      `tsc -outDir "${TSC_OUTPUT_DIR}" -declarationDir "${TYPINGS_BUILD_DIR}"`,
      {stdio: 'inherit'});
  execSync(`node scripts/tsick.js "${TSC_OUTPUT_DIR}"`, {stdio: 'inherit'});
  done();
fork icon0
star icon1
watch icon1

+ 15 other calls in file

119
120
121
122
123
124
125
126
127
128
129
 * @param {string} command Command line to run.
 * @return {Promise} Asynchronous result.
 */
async function runTestCommand(id, command) {
  return runTestTask(id, async() => {
    return execSync(command, {stdio: 'inherit'});
  });
}


/**
fork icon0
star icon1
watch icon1

+ 3 other calls in file

30
31
32
33
34
35
36
37
38
39
40
41
42
43


setTimeout(() => {




if (!fs.existsSync(envFilePath)) {
  execSync('touch .env')
}


if (!fs.existsSync(peersJsonFilePath)) {
  execSync('touch peers.json')
fork icon0
star icon1
watch icon1

+ 49 other calls in file

-3
fork icon0
star icon1
watch icon1

+ 4 other calls in file

260
261
262
263
264
265
266
267
268
269
270
}


const log = logger(23, "yellow");
function getNpmLinks() {
  const npmLsOutput = JSON.parse(
    childProcess.execSync("npm ls --depth=0 --link=true --json=true").toString()
  );
  log("npmLsOutput:\n", npmLsOutput);
  const npmLinks = Object.entries(
    _.mapValues(
fork icon0
star icon0
watch icon1

+ 7 other calls in file

54
55
56
57
58
59
60
61
62
63



async function getMotherboardSerial() {
  try {
    let result = await execSync('wmic baseboard get serialnumber');
    let output = result.toString().trim();
    return output.split(/\s+/)[1];
  } catch (error) {
    console.error(error);
fork icon0
star icon0
watch icon0

10
11
12
13
14
15
16
17
18
19
20


describe("User Registration and Login", () => {
  before(async () => {
    await initDatabase();
    try {
      execSync('npx sequelize-cli db:seed:all', { stdio: 'inherit' });
    }catch(err){
      console.log(err);
      process.exit(0);
    }
fork icon0
star icon0
watch icon1

+ 4 other calls in file

68
69
70
71
72
73
74
75
76
77
        throw new Error(message);
    }

    commands.forEach(command => {
        log.message('Running command: ' + command);
        childProcess.execSync(command, { cwd: pathToDistRepo });
    });
} else {
    log.message('\n-----(Dryrun)------\n Would have ran the following commands:\n\n' + commands.join(' &&\n') + '\n');
}
fork icon0
star icon0
watch icon1

+ 19 other calls in file

121
122
123
124
125
126
127
128
129
130
  console.error('Skipping workflow config without build option.', p);
} else {
  const cmd = `aurora workflow upload_config ${ p }`;
  await retry(async () => {
    console.log('Running:', cmd);
    const output = execSync(`aurora workflow upload_config ${ p }`);
    console.log(output.toString(), '\n')
    await setTimeoutPromise(1000);
  })
}
fork icon0
star icon0
watch icon1

49
50
51
52
53
54
55
56
57
58
// start process
const increaseVersion = '\"increase <' + commitType + '> version in package.json\"';
fs.writeFileSync('./package.json', packageJSON_new);
const increaseResult = 'package.json: "' + version_old.join('.') + '" to "' + version_new.join('.') + '" (OK)';
const cmd_add = 'git add package.json';
const gitAddResult = childProcess.execSync(cmd_add).toString();
const cmd_commit = `git commit -m "${message}"`;
const gitCommitResult = childProcess.execSync(cmd_commit).toString();
console.log('> ' + increaseVersion);
console.log(increaseResult);
fork icon0
star icon0
watch icon1