2016-01-23 11 views
8

मैं child_process.spawn stdio को संभालने के लिए कस्टम स्ट्रीम का उपयोग करना चाहता हूं।नोडजेस child_process spawn कस्टम stdio

उदाहरण

const cp = require('child_process'); 
const process = require('process'); 
const stream = require('stream'); 

var customStream = new stream.Stream(); 
customStream.on('data', function (chunk) { 
    console.log(chunk); 
}); 

cp.spawn('ls', [], { 
    stdio: [null, customStream, process.stderr] 
}); 

के लिए मैं त्रुटि Incorrect value for stdio stream मिलता है।

child_process.spawn https://nodejs.org/api/child_process.html#child_process_options_stdio के लिए प्रलेखन है। यह stdio विकल्पों के लिए कहता है कि यह स्ट्रीम ऑब्जेक्ट

स्ट्रीम ऑब्जेक्ट - एक पठनीय या लिखने योग्य स्ट्रीम साझा करें जो कि बच्चे की प्रक्रिया के साथ एक tty, फ़ाइल, सॉकेट या पाइप को संदर्भित करता है।

मुझे लगता है कि मैं इसे "संदर्भित" भाग में लापता हूं।

उत्तर

6

यह एक बग प्रतीत होता है: https://github.com/nodejs/node-v0.x-archive/issues/4030customStream स्पॉन() के लिए पारित होने पर तैयार नहीं है। आप आसानी से इस मुद्दे के आसपास जा सकते हैं:

const cp = require('child_process'); 
const stream = require('stream'); 

// use a Writable stream 
var customStream = new stream.Writable(); 
customStream._write = function (data) { 
    console.log(data.toString()); 
}; 

// 'pipe' option will keep the original cp.stdout 
// 'inherit' will use the parent process stdio 
var child = cp.spawn('ls', [], { 
    stdio: [null, 'pipe', 'inherit'] 
}); 

// pipe to your stream 
child.stdout.pipe(customStream); 
+0

हाँ, यह कुछ है जो मैं अंत में उपयोग कर रहा हूं। धन्यवाद –

+0

हालांकि यह एक अच्छा कामकाज है, वास्तविक समस्या यह है कि stdio धाराओं को एक अंतर्निहित फ़ाइल वर्णनकर्ता की आवश्यकता होती है। कस्टम धाराओं में यह नहीं है। – skerit