child_process#execSync JavaScript Examples
The following examples show how to use
child_process#execSync.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: new-starter.js From medusa with MIT License | 6 votes |
createInitialGitCommit = async (rootPath, starterUrl) => {
reporter.info(`Create initial git commit in ${rootPath}`)
await spawn(`git add -A`, { cwd: rootPath })
// use execSync instead of spawn to handle git clients using
// pgp signatures (with password)
try {
execSync(`git commit -m "Initial commit from medusa: (${starterUrl})"`, {
cwd: rootPath,
})
} catch {
// Remove git support if initial commit fails
reporter.warn(`Initial git commit failed - removing git support\n`)
fs.removeSync(sysPath.join(rootPath, `.git`))
}
}
Example #2
Source File: index.js From tunnel-tool with MIT License | 6 votes |
restart = ({ instanceid, folder }, cxt) => {
const stdout = execSync(`docker-compose -p ${instanceid} restart`, {
cwd: folder
});
cxt.logger.debug("compose.restart", {
instanceid,
folder,
stdout: stdout.toString()
});
}
Example #3
Source File: index.js From tunnel-tool with MIT License | 6 votes |
start = ({ instanceid, folder }, cxt) => {
const stdout = execSync(
`docker-compose -p ${instanceid} up --remove-orphans --detach`,
{
cwd: folder
}
);
cxt.logger.debug("compose.start", {
instanceid,
folder,
stdout: stdout.toString()
});
}
Example #4
Source File: index.js From tunnel-tool with MIT License | 6 votes |
getNameserver = () => {
const hostsRegex = new RegExp(/nameserver (.+)/, "gm");
const hosts = execSync(`cat /etc/resolv.conf`).toString();
const match = hostsRegex.exec(hosts);
if (!match) {
return null;
}
return match[1];
}
Example #5
Source File: serverAnalyzer.js From asymptoteWebApplication with GNU Lesser General Public License v3.0 | 6 votes |
// ------------------------------------------------
export function usrConnect(serverDir) {
return (req, res, next) => {
if (req.body.reqType === "usrConnect") {
let id = usrID(req.ip);
if (id !== "-1") {
var reqDest = usrDirMgr(req, serverDir, id);
makeDir(reqDest.usrAbsDirPath);
} else {
reqDest = usrDirMgr(req, serverDir, "");
}
const asyVersion = execSync('asy -c VERSION', {
timeout: 500,
encoding: "ascii"
})
const dateAndTime = dateTime();
const rawData = {
usrIP: req.ip,
usrDir: reqDest.usrDirName,
date: dateAndTime.date,
time: dateAndTime.time,
};
const logFilePath = serverDir + "/logs/log";
appendFile(logFilePath, JSON.stringify(rawData, null, `\n`))
.then(() => console.log(`log file created successfully.`))
.catch((err) => console.log(`An error occurred while writing log file!\n ${err.toString()}`));
const data = {
usrID: id,
usrConnectStatus: "UDIC",
asyVersion: asyVersion
}
res.send(data);
} else {
next();
}
}
}
Example #6
Source File: index.js From tunnel-tool with MIT License | 6 votes |
getHostname = (host, nameserver) => {
const lupRegex = new RegExp(/Address 1:\s+([^\s]+)/, "g");
const lup = execSync(`nslookup ${host} ${nameserver}`).toString();
const lups = lup.substr(lup.indexOf(host))
const match = lupRegex.exec(lups);
if (!match) {
return null;
}
return match[1];
}
Example #7
Source File: init.js From flow-js-testing with Apache License 2.0 | 6 votes |
command = {
command: "init",
describe: "Install dependencies and prepare config files",
handler: () => {
console.log("\n? Installing dependencies")
execSync("npm init --yes", {stdio: [0, 1, 2]})
execSync(
"npm install --save-dev flow-js-testing jest @babel/core @babel/preset-env babel-jest jest-environment-node",
{
stdio: [0, 1, 2],
}
)
console.log("? Generating Flow config")
execSync("flow init --reset")
console.log("? Creating Babel and Jest config files")
writeFile("./babel.config.json", babelConfig)
writeFile("./jest.config.json", jestConfig)
console.log("? Done! \n")
console.log(
"\n ? You can create new test file with 'npx flow-js-testing make' command \n"
)
},
}
Example #8
Source File: new.js From medusa with MIT License | 6 votes |
createInitialGitCommit = async (rootPath, starterUrl) => {
reporter.info(`Create initial git commit in ${rootPath}`)
await spawn(`git add -A`, { cwd: rootPath })
// use execSync instead of spawn to handle git clients using
// pgp signatures (with password)
try {
execSync(`git commit -m "Initial commit from medusa: (${starterUrl})"`, {
cwd: rootPath,
})
} catch {
// Remove git support if initial commit fails
reporter.warn(`Initial git commit failed - removing git support\n`)
fs.removeSync(sysPath.join(rootPath, `.git`))
}
}
Example #9
Source File: develop.js From medusa with MIT License | 6 votes |
export default async function ({ port, directory }) {
const args = process.argv
args.shift()
args.shift()
args.shift()
const babelPath = path.join(directory, "node_modules", ".bin", "babel")
execSync(`"${babelPath}" src -d dist`, {
cwd: directory,
stdio: ["ignore", process.stdout, process.stderr],
})
const cliPath = path.join(directory, "node_modules", ".bin", "medusa")
let child = spawn(cliPath, [`start`, ...args], {
cwd: directory,
env: process.env,
stdio: ["pipe", process.stdout, process.stderr],
})
chokidar.watch(`${directory}/src`).on("change", (file) => {
const f = file.split("src")[1]
Logger.info(`${f} changed: restarting...`)
child.kill("SIGINT")
execSync(`${babelPath} src -d dist --extensions \".ts,.js\"`, {
cwd: directory,
stdio: ["pipe", process.stdout, process.stderr],
})
Logger.info("Rebuilt")
child = spawn(cliPath, [`start`, ...args], {
cwd: directory,
env: process.env,
stdio: ["pipe", process.stdout, process.stderr],
})
})
}
Example #10
Source File: index.js From tunnel-tool with MIT License | 6 votes |
getContainersState = async ({ instanceid, folder }, cxt) => {
try {
const res = [];
const idsStr = execSync(`docker-compose -p ${instanceid} ps -q`, {
cwd: folder
})
.toString()
.trim();
const ids = idsStr.match(/[^\r\n]+/g);
for (const id of ids) {
const jsonInfoStr = execSync(
`docker inspect --format='{{json .}}' ${id}`,
{
cwd: folder
}
).toString();
const jsonInfo = JSON.parse(jsonInfoStr);
res.push(jsonInfo);
}
cxt.logger.debug("compose.instance", { res: res.map(({ Id: id }) => id) });
return res;
} catch (e) {
cxt.logger.debug("compose.container.error", { error: e.toString() });
throw e;
}
}
Example #11
Source File: editor.js From ReactSourceCodeAnalyze with MIT License | 6 votes |
function guessEditor(): Array<string> {
// Explicit config always wins
if (process.env.REACT_EDITOR) {
return parse(process.env.REACT_EDITOR);
}
// Using `ps x` on OSX we can find out which editor is currently running.
// Potentially we could use similar technique for Windows and Linux
if (process.platform === 'darwin') {
try {
const output = execSync('ps x').toString();
const processNames = Object.keys(COMMON_EDITORS);
for (let i = 0; i < processNames.length; i++) {
const processName = processNames[i];
if (output.indexOf(processName) !== -1) {
return [COMMON_EDITORS[processName]];
}
}
} catch (error) {
// Ignore...
}
}
// Last resort, use old skool env vars
if (process.env.VISUAL) {
return [process.env.VISUAL];
} else if (process.env.EDITOR) {
return [process.env.EDITOR];
}
return [];
}
Example #12
Source File: index.js From tunnel-tool with MIT License | 6 votes |
init = async (name, namespace, cxt) => {
const config = {
path: `/home/node/.kube/${name}.config`,
context: "default",
user: "handler",
host: "https://kubernetes.default.svc.cluster.local",
ca: "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt",
token: fs.readFileSync(
"/var/run/secrets/kubernetes.io/serviceaccount/token"
)
};
execSync(
`kubectl config --kubeconfig=${config.path} set-cluster ${name} --server=${config.host} --certificate-authority=${config.ca}`
);
execSync(
`kubectl config --kubeconfig=${config.path} set-credentials ${config.user} --token=${config.token}`
);
execSync(
`kubectl config --kubeconfig=${config.path} set-context ${config.context} --cluster=${name} --namespace=${namespace} --user=${config.user}`
);
execSync(
`kubectl config --kubeconfig=${config.path} use-context ${config.context}`
);
return config;
}
Example #13
Source File: ElectronRebuild.js From NoteMaster with GNU General Public License v3.0 | 6 votes |
(() => {
const nodeModulesPath = path.join(
__dirname,
'..',
'..',
'app',
'node_modules'
);
if (
Object.keys(dependencies || {}).length > 0 &&
fs.existsSync(nodeModulesPath)
) {
const electronRebuildCmd =
'../node_modules/.bin/electron-rebuild --parallel --force --types prod,dev,optional --module-dir .';
const cmd =
process.platform === 'win32'
? electronRebuildCmd.replace(/\//g, '\\')
: electronRebuildCmd;
execSync(cmd, {
cwd: path.join(__dirname, '..', '..', 'app'),
stdio: 'inherit'
});
}
})();
Example #14
Source File: index.js From tunnel-tool with MIT License | 6 votes |
start = async cxt => {
const {
services: {
config: { workerid }
}
} = cxt;
const ip = execSync("hostname -i")
.toString()
.trim();
cxt.logger.debug("worker.started", { workerid, ip });
await WorkerApi.init({ workerid, ip }, cxt);
//await WorkerApi.update(cxt);
/*(async () => {
while (true) {
await WorkerApi.update(cxt);
await Utils.Process.wait(500);
}
})().catch(e =>
cxt.logger.error("service.loop.fatal", { error: e.toString() })
);*/
}
Example #15
Source File: ElectronRebuild.js From juggernaut-desktop with MIT License | 6 votes |
(() => {
const nodeModulesPath = path.join(
__dirname,
'..',
'..',
'app',
'node_modules'
);
if (
Object.keys(dependencies || {}).length > 0 &&
fs.existsSync(nodeModulesPath)
) {
const electronRebuildCmd =
'../node_modules/.bin/electron-rebuild --parallel --force --types prod,dev,optional --module-dir .';
const cmd =
process.platform === 'win32'
? electronRebuildCmd.replace(/\//g, '\\')
: electronRebuildCmd;
execSync(cmd, {
cwd: path.join(__dirname, '..', '..', 'app'),
stdio: 'inherit'
});
}
})();
Example #16
Source File: index.js From tunnel-tool with MIT License | 6 votes |
getProcId = async (port, cxt) => {
const infoLines = execSync(`netstat -tuplen`)
.toString()
.trim();
const info = infoLines.match(/[^\r\n]+/g);
for (const ln of info) {
const portExp = /0\.0\.0\.0:(\d+)/;
const procIdExp = /(\d+)\/sshd/;
const resPort = ln.match(portExp);
const resId = ln.match(procIdExp);
if (resPort && resId) {
if (parseInt(resPort[1]) === port) {
return parseInt(resId[1]);
break;
}
}
}
return null;
}
Example #17
Source File: index.js From tunnel-tool with MIT License | 5 votes |
networkInspect = async (networkid, cxt) =>
JSON.parse(execSync(`docker network inspect ${networkid}`))
Example #18
Source File: index.js From tunnel-tool with MIT License | 5 votes |
start = async (instance, cxt) => {
const {
instanceid,
network: { networkid }
} = instance;
const networksList = execSync(`docker network ls`).toString();
if (networksList.indexOf(networkid) === -1) {
cxt.logger.debug("network.create", { networkid });
execSync(`docker network create ${networkid}`);
}
const inspect = await networkInspect(networkid, cxt);
const localhost = inspect[0].IPAM.Config[0].Gateway;
instance.network.localhost = localhost;
cxt.logger.debug("instance.network", { networkid, localhost });
const folder = path.join(cxt.workspace, "handler");
const composeFile = path.join(folder, "docker-compose.yml");
const handler = {
paths: {
folder,
composeFile
}
};
if (!fs.existsSync(handler.paths.folder)) {
fs.mkdirSync(handler.paths.folder);
}
const content = Template.compose(
instance,
cxt
);
fs.writeFileSync(handler.paths.composeFile, content);
await ComposeApi.start({ instanceid, folder: handler.paths.folder }, cxt);
instance.network.graph = await getServiceNetwork(networkid, "graph", cxt);
instance.network.web =
cxt.state.mode !== "key"
? await getServiceNetwork(networkid, "web", cxt)
: null;
return handler;
}
Example #19
Source File: index.js From tunnel-tool with MIT License | 5 votes |
networkInspect = async (networkid, cxt) =>
JSON.parse(execSync(`docker network inspect ${networkid}`))
Example #20
Source File: index.js From tunnel-tool with MIT License | 5 votes |
makePath = (pathid, cxt) => {
if (fs.existsSync(pathid)) {
return;
}
execSync(`mkdir -p ${pathid}`);
}
Example #21
Source File: index.js From tunnel-tool with MIT License | 5 votes |
kubectl = async (cmd, opts, cxt) => {
const {
config,
namespace,
input = null,
limit = 2,
output = JSON_OUTPUT
} = opts;
let currLimit = limit;
let i = 0;
while (i < currLimit) {
++i;
try {
const buildCmd = `${cmd} ${namespace ? ` -n ${namespace} ` : ""}`;
cxt.logger.debug("kubectl.cmd", { cmd: buildCmd, attempt: i });
const stdout = execSync(
(input !== null ? `echo '${input}' | ` : "") +
`kubectl ${buildCmd} ${output ? output : ""} ${
config ? ` --kubeconfig=${config} ` : ""
}`
);
if (output === null) {
return stdout;
}
if (output === JSON_OUTPUT) {
return JSON.parse(stdout);
} else {
return stdout.toString();
}
} catch (e) {
const error = e.toString();
cxt.logger.error("kubectl.error", { error });
if (i >= currLimit) {
throw e;
}
if (error.includes("was refused")) {
currLimit = 5;
await Utils.Process.wait(1000);
cxt.logger.debug("kubectl.error.retry.refuse", { attempt: i });
} else {
await Utils.Process.wait(100);
cxt.logger.debug("kubectl.error.retry", { attempt: i });
}
}
}
}
Example #22
Source File: index.js From tunnel-tool with MIT License | 5 votes |
start = async (instance, cxt) => {
const {
instanceid,
network: { networkid }
} = instance;
const networksList = execSync(`docker network ls`).toString();
if (networksList.indexOf(networkid) === -1) {
cxt.logger.debug("network.create", { networkid });
execSync(`docker network create ${networkid}`);
}
const inspect = await ComposeApi.networkInspect(networkid, cxt);
const localhost = inspect[0].IPAM.Config[0].Gateway;
instance.network.localhost = localhost;
cxt.logger.debug("instance.network", { networkid, localhost });
const folder = path.join(cxt.workspace, "handler");
const composeFile = path.join(folder, "docker-compose.yml");
const handler = {
paths: {
folder,
composeFile
}
};
if (!fs.existsSync(handler.paths.folder)) {
fs.mkdirSync(handler.paths.folder);
}
const content = Template.compose(
instance,
cxt
);
fs.writeFileSync(handler.paths.composeFile, content);
await ComposeApi.start({ instanceid, folder: handler.paths.folder }, cxt);
instance.network.graph = await ComposeApi.getServiceNetwork(networkid, "graph", cxt);
return handler;
}
Example #23
Source File: index.js From tunnel-tool with MIT License | 5 votes |
makePath = (pathid, cxt) => {
if (fs.existsSync(pathid)) {
return;
}
execSync(`mkdir -p ${pathid}`);
}
Example #24
Source File: index.js From tunnel-tool with MIT License | 5 votes |
stop = async ({ instanceid, folder }, cxt) => {
/*let retry = 0;
while (retry++ < 5) {
cxt.logger.debug("instance.stop", { retry, instanceid });
try {
const out = execSync(`docker-compose -p ${instanceid} stop`, {
cwd: folder
}).toString();
cxt.logger.debug("instance.compose.stop", { out });
break;
} catch (e) {
cxt.logger.debug("instance.stop.warning", { warning: e.toString() });
await Utils.Process.wait(2000);
}
}*/
let containers = await getContainersState({ instanceid, folder }, cxt);
let working = true;
while (working) {
cxt.logger.debug("service.worker.stopping", {
instanceid
});
working = false;
for (const container of containers) {
cxt.logger.info("service.worker.stopping");
cxt.logger.debug("service.worker.stopping.info", {
containerid: container.Id,
State: container.State
});
const out = execSync(`docker stop ${container.Id}`, {
cwd: folder
}).toString();
cxt.logger.debug("compose.stopped", {
containerid: container.Id
});
}
containers = await getContainersState({ instanceid, folder }, cxt);
for (const container of containers) {
if (container.State.Running === true) {
working = true;
}
}
await Utils.Process.wait(1000);
}
cxt.logger.debug("compose.stopped", {
instanceid
});
}
Example #25
Source File: view.js From Adachi-BOT with MIT License | 5 votes |
(async function main() {
const { argv } = yargs(hideBin(process.argv))
.usage("-n <string>")
.example("-n aby")
.help("help")
.alias("help", "h")
.version(false)
.options({
name: {
alias: "n",
type: "string",
description: "名称",
requiresArg: true,
required: false,
},
list: {
alias: "l",
type: "boolean",
description: "显示可选名称",
requiresArg: false,
required: false,
},
});
if ("string" === typeof argv.name) {
if (undefined !== mNames[argv.name]) {
const view = `genshin-${argv.name}`;
const dataFile = path.resolve(mParamsDir, `${view}.json`);
const viewFile = path.resolve(global.rootdir, "src", "views", `${view}.html`);
for (const f of [dataFile, viewFile]) {
try {
fs.accessSync(f, fs.constants.R_OK);
} catch (e) {
console.error(`错误:无法读取文件 ${f} 。`);
return -1;
}
}
const data = JSON.parse(fs.readFileSync(dataFile, "utf-8"));
if (data) {
const dataStr = JSON.stringify(data);
const param = { data: new Buffer.from(dataStr, "utf8").toString("base64") };
const url = `http://localhost:9934/src/views/${["genshin", argv.name].join("-")}.html`;
try {
execSync([puppeteer.executablePath(), `${url}?${new URLSearchParams(param)}`].join(" "));
} catch (e) {
return e.status;
}
return 0;
}
}
console.error(`错误:未知的名称 ${argv.name} ,使用 -l 查看可用名称。`);
return -1;
}
if (true === argv.list) {
const nameList = Object.keys(mNames);
if (nameList.length > 0) {
console.log(nameList.join("\n"));
return 0;
}
return -1;
}
})()
.then((n) => process.exit("number" === typeof n ? n : 0))
.catch((e) => console.log(e))
.finally(() => process.exit(-1));
Example #26
Source File: index.js From kit with MIT License | 5 votes |
/**
* @typedef {{
* main: string;
* site: {
* bucket: string;
* }
* }} WranglerConfig
*/
/** @type {import('.').default} */
export default function (options = {}) {
return {
name: '@sveltejs/adapter-cloudflare-workers',
async adapt(builder) {
const { main, site } = validate_config(builder);
const files = fileURLToPath(new URL('./files', import.meta.url).href);
const tmp = builder.getBuildDirectory('cloudflare-workers-tmp');
builder.rimraf(site.bucket);
builder.rimraf(dirname(main));
builder.log.info('Installing worker dependencies...');
builder.copy(`${files}/_package.json`, `${tmp}/package.json`);
// TODO would be cool if we could make this step unnecessary somehow
const stdout = execSync('npm install', { cwd: tmp });
builder.log.info(stdout.toString());
builder.log.minor('Generating worker...');
const relativePath = posix.relative(tmp, builder.getServerDirectory());
builder.copy(`${files}/entry.js`, `${tmp}/entry.js`, {
replace: {
SERVER: `${relativePath}/index.js`,
MANIFEST: './manifest.js'
}
});
writeFileSync(
`${tmp}/manifest.js`,
`export const manifest = ${builder.generateManifest({
relativePath
})};\n\nexport const prerendered = new Map(${JSON.stringify(
Array.from(builder.prerendered.pages.entries())
)});\n`
);
await esbuild.build({
platform: 'browser',
sourcemap: 'linked',
target: 'es2020',
...options,
entryPoints: [`${tmp}/entry.js`],
outfile: main,
bundle: true,
external: ['__STATIC_CONTENT_MANIFEST', ...(options?.external || [])],
format: 'esm'
});
builder.log.minor('Copying assets...');
builder.writeClient(site.bucket);
builder.writeStatic(site.bucket);
builder.writePrerendered(site.bucket);
}
};
}
Example #27
Source File: new.js From medusa with MIT License | 5 votes |
checkForYarn = () => {
try {
execSync(`yarnpkg --version`, { stdio: `ignore` })
return true
} catch (e) {
return false
}
}
Example #28
Source File: new-starter.js From medusa with MIT License | 5 votes |
checkForYarn = () => {
try {
execSync(`yarnpkg --version`, { stdio: `ignore` })
return true
} catch (e) {
return false
}
}
Example #29
Source File: CheckNativeDep.js From NoteMaster with GNU General Public License v3.0 | 5 votes |
(() => {
if (!dependencies) return;
const dependenciesKeys = Object.keys(dependencies);
const nativeDeps = fs
.readdirSync('node_modules')
.filter(folder => fs.existsSync(`node_modules/${folder}/binding.gyp`));
try {
// Find the reason for why the dependency is installed. If it is installed
// because of a devDependency then that is okay. Warn when it is installed
// because of a dependency
const { dependencies: dependenciesObject } = JSON.parse(
execSync(`npm ls ${nativeDeps.join(' ')} --json`).toString()
);
const rootDependencies = Object.keys(dependenciesObject);
const filteredRootDependencies = rootDependencies.filter(rootDependency =>
dependenciesKeys.includes(rootDependency)
);
if (filteredRootDependencies.length > 0) {
const plural = filteredRootDependencies.length > 1;
// eslint-disable-next-line no-console
console.log(`
${chalk.whiteBright.bgYellow.bold(
'Webpack does not work with native dependencies.'
)}
${chalk.bold(filteredRootDependencies.join(', '))} ${
plural ? 'are native dependencies' : 'is a native dependency'
} and should be installed inside of the "./app" folder.
First uninstall the packages from "./package.json":
${chalk.whiteBright.bgGreen.bold('yarn remove your-package')}
${chalk.bold(
'Then, instead of installing the package to the root "./package.json":'
)}
${chalk.whiteBright.bgRed.bold('yarn add your-package')}
${chalk.bold('Install the package to "./app/package.json"')}
${chalk.whiteBright.bgGreen.bold('cd ./app && yarn add your-package')}
Read more about native dependencies at:
${chalk.bold(
'https://github.com/electron-react-boilerplate/electron-react-boilerplate/wiki/Module-Structure----Two-package.json-Structure'
)}
`);
process.exit(1);
}
} catch (e) {
// eslint-disable-next-line no-console
console.log('Native dependencies could not be checked');
}
})();