NodeJS - 如何手动创建fs.ReadStream对象而不是fs.createReadStream?

时间:2017-09-10 16:53:13

标签: node.js socket.io stream fs

我的应用程序通过socket.io-stream接收流,我想将其用作" fs.createReadStream" object(根据NODE doc返回fs.ReadStream对象)。

我想使用" box-node-sdk"将文件上传到box.com(显然是使用传入的流内容)。这需要一个" stream"对象仅适用于" fs.createReadStream"。所以我不能直接管道传入的流,而是我必须将其转换为" fs.createReadStream"对象以便与盒子api一起使用。

例如: 而不是fs.createReadStream(' path / to / file'); //返回ReadStream对象

如何创作? myReadStream(流);

或者如何创作? fs.createReadStream(流);

你能帮我吗?



ss(socket).on('file', (stream, data) => {
        

        var streamFileName = './uploads/'+data.originalName;
		var streamDataSize = data.size;       


		//Method 1 - Using incoming stream directly:
		//Cannot use the stream directly. Not working. No error shown given by box sdk.
		client.files.uploadFile('36155801746', data.originalName, stream, (err) => {

		  if (err) {
			//done(err);
		  } else {
			//done(null, {message: 'Uploading finished'});
			console.log('Upload to box finished');
		  }

		});
		
	
		//Alternative Method 2 - Save the incoming stream into a file and again read that file. This doesn't work either. Fails for larger file size over 10 mb. setTimeout is for 3 seconds and the "boxStream" is produced with the data for 3 seconds of incoming stream.
		
		stream.pipe(fs.createWriteStream(streamFileName);
		
		//read the file again after few seconds because data is being written by the incoming steram
		setTimeout(() => {
		
          var boxStream = fs.createReadStream(streamFileName);
          client.files.uploadFile('36155801746', data.originalName, boxStream, (err) => {

              if (err) {
                //done(err);
              } else {
                //done(null, {message: 'Uploading finished'});
                console.log('Upload to box finished');
              }

            });
        }, 3000);
		



    
});




1 个答案:

答案 0 :(得分:0)

流是流; /home/pi/numbergenie/app.js:54 assistant.handleRequest(actionMap); ReferenceError: assistant is not defined at Object.<anonymous> (/home/pi/numbergenie/app.js:54:1) 返回的类型没有什么特别之处,fs.createReadStream适用于任何类型的流。

这应该有效:

box-node-sdk