在 Node JS 中访问 DOM 对象

Accessing DOM object in Node JS

我正在使用 Microsoft (https://github.com/microsoft/customvision-tfjs) Github 存储库中的代码片段在 N​​ode JS 中使用 Tensorflow.js 模型。

他们在这里使用 document.getElementById() 访问图像元素,然后将其传递给函数进行预测,但它是在 Node.js 代码之间编写的,其中 DOM 不可用.这段代码不正确吗?或者有没有办法在 Node JS

中访问 HTML 元素
const cvstfjs = require('@microsoft/customvision-tfjs');

async function doThings() {
  let model = new cvstfjs.ObjectDetectionModel();
  await model.loadModelAsync('model.json');
  const image = document.getElementById('image');
  const result = await model.executeAsync(image);
  return result;
}

doThings().then((result) => {
  console.log(result);
});

要么通过webpack在浏览器中使用TF,照常操作DOM

或者,如果您想要服务器端的乐趣,请使用 cheerio 库。

npm i cheerio

const cheerio = require('cheerio')

var html = await fs.readFile('./dong.html')

const $ = cheerio.load(html.toString())

$('#element').text()