nodejs 使用opencc 实现一个简体转台湾繁体的服务

1 篇文章 0 订阅
这篇博客介绍了如何在无法安装PHP opencc扩展的情况下,利用Node.js和OpenCC库创建一个简体中文到繁体中文的转换API,供PHP应用程序调用。首先安装Node.js和OpenCC,然后编写Node.js代码,监听8000端口并接收PHP的请求,将接收到的简体文本转换为繁体并返回。在PHP端,通过GuzzleHttp客户端发送GET请求到这个Node.js API进行转换操作。
摘要由CSDN通过智能技术生成

简体转繁体

使用场景:

app接口需要对台湾用户返回繁体, api是php开发的, 由于服务器原因不能安装上php的opencc扩展, 所以使用了nodejs 来提供一个api供php调用

首先安装好nodejs跟opencc扩展 

附: opencc github  GitHub - BYVoid/OpenCC: Conversion between Traditional and Simplified Chinese

编写代码
node.js 

const  http = require('http')
const OpenCC = require('opencc');
const converter = new OpenCC('s2t.json');
const server = http.createServer()

server.on('request', function (request, response,body) {
	    console.log('收到客户端的请求了,请求路径是:' + request.url)
	    response.setHeader('Content-Type','text/plain;charset=utf-8');
        let  post = '';
        request.on('data', function(chunk){    
         post += chunk;
       });

      request.on('end', function(){
             post = post.toString();
             converter.convertPromise(post).then((converted)=>{
                   //response.write(converted)
                   response.end(converted);
              })
          
      });

})

server.listen('8000', ()=> {console.log('8000端口已启动~')})

php 调用接口代码

<?php
namespace app;
use GuzzleHttp\Client;

class OpenCC
{

    public function transform($string)
    {
       
        try {
            $client = new Client(['base_uri' => 'http://172.xxx.xxx.xxx:8000', 
            'timeout' => 3]);
            $response = $client->get('/', ['body' => $string]);
            
            if ($response->getStatusCode() == 200) {
                return $response->getBody()->getContents();
            } else {
                throw new \Exception('convert fail');
            }
        } catch (\Exception $e) {
            Log::write($e->getMessage());
        }
        return $string;
   }    

}

启动node.js 

放开8000端口

调用预览

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值