gpt4 book ai didi

node.js - Foreach 数组并在回调中使用数组成员

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:48 25 4
gpt4 key购买 nike

我有远程文件地址数组。我只是在 foreach 数组中使用 for ,并在 foreach 的主体中,启动 HTTP GET 请求来下载数据。但一切都是异步的,我需要知道文件名才能在请求回调中保存文件。

解决这个问题的最佳实践是什么?

演示代码:

files = ["url.com/file.png", "url.com/file.doc"]

for file in files
req = http.get file, (response) =>
response.setEncoding 'binary'
body = ""

response.on "data", (chunk) =>
body += chunk

response.on "end", () =>
#Here I needs to know the file name to save it
fs.writeFileSync @currentFolder + "/Files/" + file, body, "binary"

谢谢!

最佳答案

你必须确定它的范围。使用这样的函数:

files = ["url.com/file.png", "url.com/file.doc"]

for file in files
((file) ->
req = http.get file, (response) =>
response.setEncoding 'binary'
body = ""

response.on "data", (chunk) =>
body += chunk

response.on "end", () =>
fs.writeFileSync @currentFolder + "/Files/" + file, body, "binary"
).call @, file

关于node.js - Foreach 数组并在回调中使用数组成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16185972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com