Skip to content

Instantly share code, notes, and snippets.

@jshbrntt
Last active April 9, 2021 16:11
Show Gist options
  • Save jshbrntt/b944aed624fcfea231ba9f492841fb3d to your computer and use it in GitHub Desktop.
Save jshbrntt/b944aed624fcfea231ba9f492841fb3d to your computer and use it in GitHub Desktop.
gRPC + JSON in Node.js
const process = require('process');
const grpc = require('@grpc/grpc-js');
/**
* $ node grpc.js server
*
* Server listening { port: 9001 }
* Received { request: { message: 'Hello Server!' } }
*
* $ node grpc.js client
*
* Received { response: { message: 'Hello Client!' } }
*/
const [command] = process.argv.slice(2);
const serialize = value => Buffer.from(JSON.stringify(value));
const deserialze = buffer => JSON.parse(buffer.toString());
if (command === 'client') {
const client = new grpc.Client('localhost:9001', grpc.credentials.createInsecure());
client.waitForReady(Infinity, error => {
if (error) {
console.log(error);
process.exit(1);
}
const requestBody = {
message: 'Hello Server!'
};
client.makeUnaryRequest(
'/sayHello',
serialize,
deserialze,
requestBody,
(error, response) => {
if (error) {
console.error(error);
process.exit(1);
}
console.log('Received', { response });
}
);
});
}
if (command === 'server') {
const server = new grpc.Server();
server.addService({
sayHello: {
path: '/sayHello',
requestStream: false,
responseStream: false,
requestSerialize: serialize,
responseSerialize: serialize,
requestDeserialize: deserialze,
responseDeserialize: deserialze
}
}, {
sayHello: (call, callback) => {
const { request } = call;
console.log('Received', {
request
});
return callback(null, {
message: 'Hello Client!'
});
}
});
server.bindAsync('0.0.0.0:9001', grpc.ServerCredentials.createInsecure(), (error, port) => {
if (error) {
console.error(error);
process.exit(1);
}
server.start();
console.log('Server listening', { port });
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment