如何强制此Nodejs功能等到Fs.WriteFile完成?

发布于 2025-02-09 19:07:30 字数 1656 浏览 1 评论 0 原文

我根据这些说明正在实现https.request()除非做一个stdout,否则我写的是文件。我希望结束等到文件编写过程完成。我该怎么做?

 process.stdout.write(d);

将其更改为

fs.writeFile(path, d, err => {
   if (err) {
     console.error(err);
   } else {
     console.log("data => " path)
   }            
})

整个代码

const https = require('node:https');

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET'
};

const req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});
req.end();

更新

MTN发布了一种有效的解决方案,但我意识到我的代码稍微复杂得多。我以块读取该文件,然后在最后保存。 MTN的解决方案很早完成。这是代码。谁能帮我修复它?

    const request = https.request(url, (response, error) => {
      if (error) {console.log(error)}
      let data = '';
    
      response.on('data', (chunk) => {
        data = data + chunk.toString();
      });
  
      response.on('end', () => {
        fs.writeFile(path, data, err => {
          if (err) {
            console.error(err);
          } else {
            console.log("data => " path)
          }            
        })
      })
    })
  
    request.on('error', (error) => {
      console.error(error);
    })

    request.end()
  },

I am implementing https.request per these instructions (https://nodejs.org/api/https.html#httpsrequesturl-options-callback) except instead of doing a stdout, I am writing to file. I want the end to wait until the file writing process is complete. How can I do this?

 process.stdout.write(d);

is changed to

fs.writeFile(path, d, err => {
   if (err) {
     console.error(err);
   } else {
     console.log("data => " path)
   }            
})

This is the entire code

const https = require('node:https');

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET'
};

const req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});
req.end();

UPDATE

MTN posted a solution that works, but I realized that my code is slightly more complex. I read the file in chunks and save at the end. MTN's solution finishes early. Here is the code. Can anyone help me fix it?

    const request = https.request(url, (response, error) => {
      if (error) {console.log(error)}
      let data = '';
    
      response.on('data', (chunk) => {
        data = data + chunk.toString();
      });
  
      response.on('end', () => {
        fs.writeFile(path, data, err => {
          if (err) {
            console.error(err);
          } else {
            console.log("data => " path)
          }            
        })
      })
    })
  
    request.on('error', (error) => {
      console.error(error);
    })

    request.end()
  },

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

苯莒 2025-02-16 19:07:30

直接的答案是,在您的 console.log 之后,编写文件后应该发生的任何事情都必须进入回调。 (不过,您的代码中没有任何东西可以在之后运行。)


但是:

您的代码会更简单。

  1. 如果您要...

    使用库发送HTTP请求而不是RAW > https 模块。 (例如: got axios node -fetch ,...) - 不仅要照顾诸如阅读身体之类的事情对于您来说,它们也有一个承诺接口,使您可以执行第2点。

  2. 重写代码以使用 async /等待

这是一个示例, got

import got from 'got'
import { writeFile } from 'fs/promises'

const response = await got('https://encrypted.google.com').text()
await writeFile('test.html', response)

// Whatever should happen after the file was written would simply go here!

注意: ES6模块是因为我使用了顶级等待 import ,而 got 甚至不再支持commonj。因此,要么您的 package.json 必须具有“ type”:“ module” ,要么必须是 mjs

The immediate answer would be that whatever should happen after the file was written would have to go into the callback, after your console.log. (There is nothing in your code that looks like it's supposed to run afterwards though.)


But:

Your code would be a lot simpler if you'd...

  1. Use a library for sending HTTP requests instead of the raw https module. (For example: got, axios, node-fetch, ...) - Not only do these take care of things like reading the body for you, they also have a promise interface which allows you to do point 2.

  2. Rewrite the code to uses async/await.

Here is an example with got:

import got from 'got'
import { writeFile } from 'fs/promises'

const response = await got('https://encrypted.google.com').text()
await writeFile('test.html', response)

// Whatever should happen after the file was written would simply go here!

Note: This has to be an ES6 module because I used top-level await and import, and got doesn't even support CommonJS anymore. So either your package.json would have to have "type": "module" or the file ending would have to be mjs.

木落 2025-02-16 19:07:30

您可以改用 fs.writefilesync()。它的同步,因此等待写作完成

You can use fs.writeFileSync() instead. Its sync so it waits for the writing to be finished

笙痞 2025-02-16 19:07:30
res.on(“data”, (d) => { fs.writeFile(/* Enter params here */ })

在fs.writefile中,在最后一个回调函数中添加您想做的任何事情。

res.on(“data”, (d) => { fs.writeFile(/* Enter params here */ })

Inside the fs.writeFile, add whatever you want to do in the last callback function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文