I have not much idea about JavaScript but I really like the Node-Red framework to connect to IoT devices. I've built a small flow that connects an http-request node (to get a picture) to a function node and the function node to a msg-debug node (to see what is going on).
The picture is successfully grabbed by the request node and I used this javascript function in the function node to send the payload (image) off to IPFS to upload it and to get the hash of the uploaded file back but it doesn't work. What am I doing wrong?
Note, the IPFS daemon is up and running on my machine on: http://localhost:5001/
I've tried different scripts (from node.js or other online examples) but none worked.
Here is the code in the function node:
//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;
The message object that I get from the msg-debug node in the end looks like this:
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]