I am trying to create a ReactNative project with ReactNative CLI. So i am triggering the command in a nodejs script.
We also encounter prompts during the project creation and that has been handled in my code below:
const execWithSpawn = (command, args, options, promptResponses) => {
return new Promise((resolve, reject) => {
const child = spawn(command, args);
let stdout = '';
let stderr = '';
console.log(`Spawning process: ${command} ${args?.join(' ')}`);
child.stdout.on('data', (data) => {
stdout += data.toString();
console.log(`stdout: ${data}`);
// Check for prompts and respond if needed
if (promptResponses) {
for (const prompt of Object.keys(promptResponses)) {
if (data.toString().includes(prompt)) {
const response = promptResponses[prompt];
child.stdin.write(`${response}n`);
console.log(`Responded to prompt "${prompt}" with: ${response}`);
break; // Respond to only the first matching prompt
}
}
}
});
child.stderr.on('data', (data) => {
stderr += data.toString();
console.error(`stderr: ${data}`);
});
child.on('close', (code) => {
console.log(`Process closed with code: ${code}`);
if (code === 0) {
resolve({ stdout, stderr });
} else {
reject(new Error(`Process exited with code ${code}`));
}
});
child.on('error', (err) => {
console.error(`Process error: ${err.message}`);
reject(err);
});
});
};
execWithSpawn(
'npx' ['react-native', 'init', '--version', '70.0.0'],
undefined, { 'Install cocopods': 'N' }
);
But even after the project is created, the program is not exiting. Also close and exit events are not fired for the child.
NOTE:
This command creates lot of output. So to increate the buffer size, i have configured maxBuffer
size but still the behaviour is same. Also this command exits properly if i run in a shell normally.