Cú pháp để sinh sản là:
spawn(<command>, [array of arguments]);
Ví dụ:thực hiện ls lệnh với -l /home các tùy chọn sẽ như thế này:
ls = spawn('ls', ['-l', '/home'];
Vì vậy, spawn('mongoexport',['--csv']); đang đi đúng hướng nhưng mongoexport --csv không hợp lệ. Đó là lý do tại sao bạn gặp lỗi. mongoexport không chỉ cần --csv . Giống như những gì bạn đã làm ở trên, bạn cần chỉ định tên cơ sở dữ liệu (-d "lms" ), tên bộ sưu tập (-c "databases" ), tên trường (--fields firstname,lastname ), và v.v.
Trong trường hợp của bạn, nó phải là một cái gì đó như thế này:
var spawn = require('child_process').spawn;
app.get('/export', function(req, res) {
var mongoExport = spawn('mongoexport', [
'--db', 'lms', '--collection', 'databases',
'--fields',
'firstname,lastname,email,daytimePhone,addressOne,city,state,postalCode,areaOfStudy,currentEducationLevel,company',
'--csv'
]);
res.set('Content-Type', 'text/plain');
mongoExport.stdout.on('data', function (data) {
if (data) {
// You can change or add something else here to the
// reponse if you like before returning it. Count
// number of entries returned by mongoexport for example
res.send(data.toString());
} else {
res.send('mongoexport returns no data');
}
});
}