.Net Core-调用NodeJs(NodeService)
需求:在服务器端使用js渲染引擎arttemplate,生成HTML。以实现在后台配置模板,动态生成HTML
微软提供了Microsoft.AspNetCore.NodeServices这个库,专门用来调用nodejs服务
1、安装包Microsoft.AspNetCore.NodeServices、安装nodejs
2、在ConfigureServices方法中添加 services.AddNodeServices();
3、注入INodeServices服务,通过模板获取html
public async Task<IActionResult> Index([FromServices]INodeServices nodeService) { //js模板 var htmlTemplate = @" OrderID:{{model.ID}}<br> UserName:{{model.UserName}}<br> {{each model.OrderItems as item index}} {{item.OrderID}}-{{item.Price}} {{/each}}"; //数据 var orderModel = new Order { ID = 1, UserName = "fan", OrderItems = new List<OrderItem> { new OrderItem { OrderID = 1, Price = 10.00M }, new OrderItem { OrderID = 1, Price = 15.00M }, new OrderItem { OrderID = 1, Price = 13.00M } } }; var orderJSON = JsonConvert.SerializeObject(orderModel); //获取html string html = await nodeService.InvokeAsync<string>("./nodejs_handler.js", htmlTemplate, orderJSON); return View(); }
项目根目录添加nodejs_handler.js
const template = require('art-template'); module.exports = function (callback, htmlTemplate, dataJSON) { var compile = template.compile(htmlTemplate); var html = compile({ "model": JSON.parse(dataJSON) }); callback(null, html); }
4、在项目根目录安装art-template的npm包
npm install art-template
5、完成,运行即可