如何使用 Node.js 读取外部文本文件?

所以我正在尝试读取外部(如来自不同域的)文本文件,但我尝试过的任何内容都不起作用。

通常发生的是响应是undefined,或者根本没有。

这是我尝试过的一件事:


// package xmlhttprequest is installed

// this was copy-pasted from some other stackoverflow question

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

var txtFile = new XMLHttpRequest();


txtFile.open("GET", "https://snappeathing282346239557829348747259837723489.000webhostapp.com/pin.txt", true);

txtFile.onreadystatechange = function() {

  if (txtFile.readyState === 4) {  // Makes sure the document is ready to parse.

    if (txtFile.status === 200) {  // Makes sure it's found the file.

      allText = txtFile.responseText; 

      lines = txtFile.responseText.split("\n"); // Will separate each line into an array

    }

  }

}

console.log(txtFile.send(null)) // Logs response to console

我得到的回应是undefined,我怎样才能得到 123(123 是 txt 文件包含的内容)而不是记录undefined?


宝慕林4294392
浏览 187回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript