LoginSignup
19
20

More than 5 years have passed since last update.

.NET MVC(C#)からjavascriptやnodejsを実行して戻り値を取得する

Last updated at Posted at 2016-04-26

Edge.jsはnode.jsとC#やpythonなどを混在してプログラミングしちゃおうみたいなそんなやつみたいです。

今回はC#からnode.jsを実行したかったので使ってみました。
.NET MVCでAPIを書いている想定です。

NuGetでインストールしましょう。


Install-Package Edge.js

C#のクラスからjavascriptファイルを呼び出してみる

形態素解析してみたかったんですが、NMecabに辞書機能がないっぽいので、rakutenma.jsを使ってみました。

Controllers/HogeController.cs

using EdgeJs;
public class HogeController :ApiController
{
    public async Task<string> Get()
    {
        var arg = "test";
        var result = await Edge.Func(this.JsSource("rakutenma_tokenize.js"))(arg);
        return result.ToString();
    }
    public string JsSource(string path)
    {
        var rootPath = System.Web.HttpContext.Current.Server.MapPath("/");
        return "return function (data, callback) {" + File.ReadAllText($"{rootPath}/Scripts/{path}") + "}";
    }
}
Scripts/rakutenma_tokenize.js
callback(null, 'Node.js ' + process.version + ' welcomes ' + data);

以下のような文字列が返る

Node.js v5.9.1 welcomes test

npm から取得したrakutenma.jsを使う

rakutenma.js

packagesフォルダがあるところで
wwwroot直下で
npm install rakutenma --save
します。
(node_modulesをどこに置くべきなのかわかりませんが、deploy時にも一緒にアップロードする必要がありそうでしたので、ここにしたら動きました)

Scripts/rakutenma_tokenize.js を書き換えます。

Scripts/rakutenma_tokenize.js
var RakutenMA = require('rakutenma');
/* __dirname は bin/edge だった */
var model = require('../../node_modules/rakutenma/model_ja.json');
var rma = new RakutenMA(model, 1024, 0.007812);
rma.featset = RakutenMA.default_featset_ja;
rma.hash_func = RakutenMA.create_hash_func(15);

var message = rma.tokenize('彼は新しい仕事できっと成功するだろう。');


callback(null, 'result = ' + JSON.stringify(message));

以下のような文字列が返る

result = [["彼","D"],["は","P-rj"],["新しい","A-c"],["仕事","N-nc"],["で","P-k"],["きっと","F"],["成功","N-nc"],["する","V-dp"],["だろう","X"],["。","M-p"]]

なんか動いてるっぽい感じです!!やった

追記

同じことやってる人いた!!用途までかぶっているとは
http://tamafuyou.hatenablog.com/entry/2016/04/10/045238

19
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
20