我可以在javaScript中使用从Node.js抓取的文件吗?
我是javaScript新手,正在尝试使用node.js对网站进行爬网。我可以检查控制台日志中的数据,但希望使用另一个javaScript文件中的数据。如何获取数据 问题是我从未使用过node.js。我使用javaScript,因此我知道如何编写代码,但我不知道后端或服务器如何工作 我尝试在本地主机中打开它,但节点方法(例如require)不起作用。我发现这是因为节点在浏览器中不工作。看到了吗?对js来说非常陌生 我应该用bundler还是别的什么 我以为是 以某种方式将数据作为json发送 以某种方式获取json数据并呈现 这是爬行代码文件 const axios=要求性; const cheerio=requirecheerio; const log=console.log; const getHtml=async=>{ 试一试{ 返回wait axios.getURL; }捕捉错误{ 控制台错误; } }; 获取HTML .thenhtml=>{ 设ulList=[]; const$=cheerio.loadhtml.data; const$bodyList=$div.info-ul.childrenli; $bodyList.eachfunctioni,elem{ 乌利斯特[i]={ 屏幕:$this.find'a'.attr'data-screenname', 时间:$this.find'a'.attr'data-playstarttime' }; }; const data=ulList.filtern=>n.time; 返回数据; } .thenres=>logres; 你能解释一下我应该采取什么措施吗 另外,如果我能理解为什么需要这些步骤,那就太好了我可以在javaScript中使用从Node.js抓取的文件吗?,javascript,node.js,json,web-crawler,Javascript,Node.js,Json,Web Crawler,我是javaScript新手,正在尝试使用node.js对网站进行爬网。我可以检查控制台日志中的数据,但希望使用另一个javaScript文件中的数据。如何获取数据 问题是我从未使用过node.js。我使用javaScript,因此我知道如何编写代码,但我不知道后端或服务器如何工作 我尝试在本地主机中打开它,但节点方法(例如require)不起作用。我发现这是因为节点在浏览器中不工作。看到了吗?对js来说非常陌生 我应该用bundler还是别的什么 我以为是 以某种方式将数据作为json发送 以
非常感谢 您可以尝试将数据写入JSON文件并继续,这是一种方法,然后您可以将数据用作任何js文件中的对象
const appendFile = (file, contents) =>
new Promise((resolve, reject) => {
fs.appendFile(
file,
contents,
'utf8',
err => (err ? reject(err) : resolve()),
);
});
getHtml()
.then(html => {
let ulList = [];
const $ = cheerio.load(html.data);
const $bodyList = $("div.info-timetable ul").children("li");
$bodyList.each(function(i, elem) {
ulList[i] = {
screen: $(this).find('a').attr('data-screenname'),
time: $(this).find('a').attr('data-playstarttime')
};
});
const data = ulList.filter(n => n.time);
return data;
})
.then(res => {
return appendFile('./data.json',res.toString())
}))
.then(done => {log('updated data json')});
爬网代码文件在那里,所以您使用的是节点服务器,对吗?您只需要将数据导出到需要的另一个文件中。或者更好的是只导出爬行并返回数据的函数。