11defmodule NodeJS.Worker do
22 use GenServer
33
4+ # Port can't do more than this.
5+ @ read_chunk_size 65_536
6+
47 @ moduledoc """
58 A genserver that controls the starting of the node service
69 """
@@ -21,15 +24,42 @@ defmodule NodeJS.Worker do
2124 @ doc false
2225 def init ( module_path ) do
2326 node = System . find_executable ( "node" )
24- port = Port . open ( { :spawn_executable , node } , env: [ { 'NODE_PATH' , String . to_charlist ( module_path ) } ] , args: [ node_service_path ( ) ] )
27+
28+ port =
29+ Port . open (
30+ { :spawn_executable , node } ,
31+ line: @ read_chunk_size ,
32+ env: [
33+ { 'NODE_PATH' , String . to_charlist ( module_path ) } ,
34+ { 'WRITE_CHUNK_SIZE' , String . to_charlist ( "#{ @ read_chunk_size } " ) }
35+ ] ,
36+ args: [ node_service_path ( ) ]
37+ )
38+
2539 { :ok , [ node_service_path ( ) , port ] }
2640 end
2741
42+ defp get_response ( data \\ '' ) do
43+ receive do
44+ { _ , { :data , { flag , chunk } } } ->
45+ data = data ++ chunk
46+
47+ case flag do
48+ :noeol -> get_response ( data )
49+ :eol -> data
50+ end
51+ end
52+ end
53+
2854 @ doc false
2955 def handle_call ( { module , args } , _from , [ _ , port ] = state ) when is_tuple ( module ) do
3056 body = Jason . encode! ( [ Tuple . to_list ( module ) , args ] )
3157 Port . command ( port , "#{ body } \n " )
32- response = receive do { _ , { :data , data } } -> decode ( data ) end
58+
59+ response =
60+ get_response ( )
61+ |> decode ( )
62+
3363 { :reply , response , state }
3464 end
3565
0 commit comments