简体   繁体   English

如何使用node.js从API调用打开数据并将数据写入文件

[英]How to open and write data into file from API call using node.js

I wrote an API and the response from that API is array of data. 我编写了一个API,该API的响应是数据数组。 Whenever the response coming from that API i want to store that response in file that is.txt format. 每当来自该API的响应时,我都希望将该响应存储在is.txt格式的文件中。 I tried but it shows an error like "No such directory or NO such path". 我试过了,但是显示了类似“没有这样的目录或没有这样的路径”的错误。 How to create file and write data into file from API using node.js. 如何使用node.js从API创建文件并将数据写入文件。 This is the code i wrote : 这是我写的代码:

    exports.Entry = functions.https.onRequest((req, res) => {
      var fs = require('fs');
      var a = ['6', '7', '8'];
      var b = ['22', '27', '20'];
      var eachrecord = [];

      for (var i = 0; i < a.length; i++) {
        eachrecord += a + b;
      }

      console.log("eachrecord is", eachrecord);

      //Writing each record value into file
     fileWriteSync('./filewriting1.txt');
     function fileWriteSync(filePath){
  var fd = fs.openSync(filePath,'w');
  var length = eachrecord.length;
  for(i = 0;i<length;i++){
    var eachrecordwrite = fs.writeSync(fd,eachrecord[i] + '\n',null,null);

    console.log("hii",eachrecord[i]);

  }
  fs.closeSync(fd);
}
    });

How to write data into file from API using node.js 如何使用node.js从API将数据写入文件

You can only write files to os.tmpdir() , which is /tmp on Cloud Functions. 您只能将文件写入os.tmpdir() ,在Cloud Functions上为/tmp /tmp is a memory based filesystem. /tmp是基于内存的文件系统。 Everything else is read-only. 其他所有内容均为只读。 If you don't intend to do anything with that written file, it will consume memory indefinitely. 如果您不打算对该写入文件做任何事情,它将无限期地消耗内存。 You should always delete files written to /tmp before the function terminates. 函数终止之前,应始终删除写入/tmp文件。 Writing a file to memory like this is almost certainly not the best solution to a problem, unless there is a consumer for that content that can only read it off the local filesystem. 像这样将文件写入内存几乎肯定不是解决问题的最佳方法,除非该内容的使用者仅能从本地文件系统读取该内容。

Since you haven't really said what problem you're trying to solve, it's not possible to say what you could be doing instead (that's something for a different question). 由于您尚未真正说出要解决的问题,因此无法说出要做什么(这是另一个问题的意思)。 But anyway, you can only write to /tmp . 但是无论如何,您只能写入/tmp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM