我正在使用spawn模块并执行curl命令并从服务器获取JSON响应。这是我的代码 -
var spawn = require('child_process').spawn;
log.debug("Executing curl command for getting all artifacts");
var artifacts_data = spawn('bash module_features/init_get_all_artifacts.sh', [
host_url, access_token, project_id
], {
shell: true
});
artifacts_data.stdout.setEncoding('utf8');
var stdout = "";
artifacts_data.stdout.on('data', (data) => {
stdout += data.toString();
try {
var artifact_array = JSON.parse(stdout);
log.debug(artifact_array);
if (artifact_array != null || artifact_array != undefined){
res.send(200, { status: 'success', message: artifact_array });
}else{
log.debug('Artifact list not found.');
res.send(400, { status: 'error', message: 'In else :: somthing went wrong' });
}
} catch (error) {
log.debug("There was some error in parsing artifacts JSON");
res.send(400, { status: 'error', message: 'somthing went wrong' });
}
});
但是,我得到一半字符串(8192个字符),这是不正确的JSON。 请帮我增加stdout的字符限制或任何替代解决方案。
感谢任何帮助。
答案 0 :(得分:0)
我解决了这个问题。
var data = '';
artifacts_data.stdout.on('data',(data) => {
stdout += data.toString();
});
artifacts_data.stdout.on('end',(data) => {
try {
var artifact_array = JSON.parse(stdout);
log.debug(artifact_array);
if (artifact_array != null || artifact_array != undefined){
res.send(200, { status: 'success', message: artifact_array });
}else{
log.debug('Artifact list not found.');
res.send(400, { status: 'error', message: 'In else :: somthing went wrong' });
}
} catch (error) {
log.debug("There was some error in parsing artifacts JSON");
res.send(400, { status: 'error', message: 'somthing went wrong' });
}
});
如果我们在Web应用程序中处理IO,我们必须坚持使用异步方法。
答案 1 :(得分:0)
iSmita建议的end
事件的问题在于它仅在进程退出时才触发。因此,您会失去反应能力,尤其是在您希望得到多个答案的情况下。
如果消息以\n
结尾,您可以执行以下更通用的操作:
let stdoutBuffer = ""
// Stdout messages catching
process.stdout.on('data', (data) => {
data = data.toString() // Convert chunk to string
// Add too buffer but no process util the end
stdoutBuffer += data
// Split if several lines at once
const answers = stdoutBuffer.split('\n')
// Send the last part to the buffer.
// If the end was '\n' so the buffer will be set back with an empty string.
// If their is no '\n' so the buffer won't be consumed and answers will be empty.
stdoutBuffer = answers.pop()
answers.forEach((a) => {
// do some stuff with the answer
})
})