A Node.js application demonstrating bidirectional streaming using gRPC with three services:
- Greet Service
- Calculator Service
- Blog Service
- Node.js (v16 or later)
- gRPC Tools
- Protobuf Compiler
- Docker (for MongoDB)
- Clone the repository:
git clone https://github.com/mariscalromeroalejandro/gRPC-nodejs
cd grpc-nodejs- Install dependencies:
npm installTo generate the gRPC client and server code from .proto files, run:
npm run pb:genThis command uses the gen.sh script located in the scripts folder and processes greet, calculator, and blog services.
To enable TLS/SSL, set the tls variable to true in both the client and server main() functions. Ensure the following files are available in the ./ssl directory:
ca.crt- Root Certificateserver.crt- Server Certificateserver.pem- Private Key
Run the ssl:gen script to generate these files:
npm run ssl:gen- Start the Greet Server:
npm run greet:server- Run the Greet Client:
npm run greet:client- Start the Calculator Server:
npm run calculator:server- Run the Calculator Client:
npm run calculator:clientThe Blog Service demonstrates CRUD operations with MongoDB using gRPC.
Before running the Blog Service, start MongoDB using Docker:
npm run blog:dbnpm run blog:servernpm run blog:clientEach service has its own client implementation located in its respective folder (greet/client, calculator/client, blog/client).
Example usage for the Blog client:
function main() {
const creds = grpc.credentials.createInsecure();
const client = new BlogServiceClient('localhost:50051', creds);
const req = new Blog()
.setAuthorId('Alex')
.setTitle('My First Blog')
.setContent('This is a sample blog post.');
client.createBlog(req, (err, res) => {
if (err) {
console.error('Error:', err.message);
return;
}
console.log('Blog created with ID:', res.getId());
});
}
main();grpc-nodejs/
├── greet/
│ ├── client/
│ ├── server/
│ └── proto/
├── calculator/
│ ├── client/
│ ├── server/
│ └── proto/
├── blog/
│ ├── client/
│ ├── server/
│ ├── proto/
│ └── docker-compose.yml
├── scripts/
│ └── gen.sh
├── ssl/
│ └── (SSL Certificates)
├── package.json
└── README.md
@grpc/grpc-js: gRPC library for Node.jsgoogle-protobuf: Protocol Buffers library for Node.jsgrpc-tools: Tools for compiling.protofilesmongodb: MongoDB driver for Node.js
ISC
Alejandro Mariscal Romero