Skip to content

Instantly share code, notes, and snippets.

@occar421
Last active March 27, 2018 05:05
Show Gist options
  • Save occar421/562d94b10f708a1f44c2229f7ae57fdb to your computer and use it in GitHub Desktop.
Save occar421/562d94b10f708a1f44c2229f7ae57fdb to your computer and use it in GitHub Desktop.
const fs = require('fs-extra');
const path = require('path');
const {spawn} = require('child_process');
(async () => {
const base = path.join(__dirname, 'sandbox');
await fs.mkdirp(base);
await fs.outputFile(path.join(base, 'foo.txt'), 'FOO');
await fs.outputFile(path.join(base, 'bar.txt'), 'BAR');
const results = await fs.readdir(base)
.then(dirs => dirs.filter(d => d.startsWith('foo')))
.then(dirs => dirs.map(d => path.join(base, d)));
for (const r of results) {
const process = spawn('ping', ['google.com'], {shell: true});
function promiseFromChildProcess(child) {
return new Promise(function (resolve, reject) {
child.addListener("error", reject);
let flag = false;
child.stdout.addListener("close", () => {
if (flag) {
resolve();
}
flag = true;
});
child.stderr.addListener("close", () => {
if (flag) {
resolve();
}
flag = true;
});
});
}
process.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
process.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
process.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
await promiseFromChildProcess(process);
}
console.log('aaa');
await fs.remove(base);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment