我对JavaScript不是很了解,但我真的很喜欢Node-Red框架来连接IoT设备。我构建了一个小流程,将http-request节点(以获取图片)连接到功能节点,并将功能节点连接到msg-debug节点(以查看发生了什么)。
请求节点成功捕获了图片,我在函数节点中使用了这个javascript函数,将有效负载(图像)发送到IPFS,上传它并获取上传文件的散列,但它不起作用。我做错了什么?
注意,IPFS守护进程已经启动并在我的机器上运行:http://localhost:5001/
我尝试过不同的脚本(来自node.js或其他在线示例),但都不起作用。
以下是函数节点中的代码:
//const ipfsAPI = require('ipfs-api');
var payload=msg.payload;
function toIPFS(file) {
return new Promise(resolve => {
const reader = new FileReader();
reader.onloadend = function() {
const ipfs = IpfsApi('ipfs', 5001,{protocol : "http"}) // Connect to IPFS
const buf = buffer.Buffer(reader.result) // Convert data into buffer
ipfs.files.add(buf, (err, result) => { // Upload buffer to IPFS
if(err) {
return "error";
}
let url = `https://ipfs.io/ipfs/${result[0].hash}`
resolve('resolved url');
})
}
reader.readAsArrayBuffer(file); // Read Provided File
//console.log(`done!!!!`)
});
}
//var test = toIPFS(payload);
toIPFS(payload);
return msg;最后,我从msg-debug节点获得的消息对象如下所示:
object
_msgid: "80561394.e873e"
topic: ""
payload: ""
statusCode: 200
headers: object
accept-ranges: "bytes"
access-control-allow-origin: "*"
access-control-expose-headers: "Content-Length"
cache-control: "max-age=604800, must-revalidate"
content-type: "image/jpeg"
date: "Sun, 16 Jun 2019 16:39:46 GMT"
last-modified: "Thu, 28 Jun 2018 04:32:21 GMT"
server: "ECS (lcy/1D6A)"
strict-transport-security: "max-age=631138519"
surrogate-key: "media media/bucket/2 media/1012192454752301056"
x-cache: "HIT"
x-connection-hash: "4d2ce5d9ed372dccc93b26cf6e8ce8c4"
x-content-type-options: "nosniff"
x-response-time: "460"
content-length: "127686"
connection: "close"
x-node-red-request-node: "6f2e7990"
responseUrl: "https://upload.wikimedia.org/wikipedia/commons/1/12/K2_2006b.jpg"
redirectList: array[0]发布于 2019-06-17 15:53:59
应该不需要任何文件处理,因为您已经将文件的内容放在一个缓冲区中(在msg.payload中)。
因此,您应该能够直接调用:
const ipfs = IpfsApi('ipfs', 5001,{protocol : "http"})
ipfs.files.add(buf, (err, result) => {
msg.payload = result[0].hash;
node.send(msg)
})(假设您已经将ipfs模块添加到global context中,因此它在作用域中。)
https://stackoverflow.com/questions/56621026
复制相似问题