简体   繁体   中英

async and await function Node.js

I have followed this tutorial to upload files into IPFS using Node.js, but I had a problem which doesn't appear in the tutorial, It is related to with Async and await function, I can't make this statement

const fileHash = fileAdded[0].hash;

I tried with await

const fileAdded = await ipfs.add({path: Name, content: file});

but unfortunately, I got an error which is (hash undefined).

I tried with a callback function, but I'm not sure about my way because (fileAdded) variable didn't give me any answer and also it was undefined,

this is a full code:

const ipfsClient = require('ipfs-http-client');
const express = require('express');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
const fs= require('fs');

const ipfs = new ipfsClient({host: 'localhost', port: '5001', protocol: 'http'});
const app= express();
var hash = require('hash');

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(fileUpload());

app.get('/',(req,res)=>{
    res.render('home');
});

app.post('/upload',(req,res)=>{
    const f= req.files.file;
    const Name = req.files.file.name;
    const filePath ="files/"+ Name;

    f.mv(filePath,async(err)=>{

        if(err){
            console.log("error failed to download a file");
            return res.status(500).send(err);
        }

        const fileh = await addFile(Name,filePath);

        fs.unlink(filePath, (err)=>{
            if(err) console.log("error");
        });

        res.render('upload',{Name,fileh});
    });
});

const addFile= async(Name,filePath)=> {
    const file=fs.readFileSync(filePath);

    const fileAdded = await ipfs.add({path: Name, content: file});

    const fileHash = fileAdded[0].hash;

    return fileHash;
};

app.listen(3000,()=>{
    console.log("server is listen");
}); 

this is the error appears:

错误信息 i write a callback function like that:

const addFile= async(Name,filePath)=> {
const file=fs.readFileSync(filePath);


const fileAdded = await ipfs.add({path: Name, content: file},(err,res)=>{
    if(err)
    console.log(err);


const fileHash = fileAdded[0].hash;

return fileHash;});};

but the value of fileAdded and fileHash was undefined.

after i use this code from @Always Learning:

  const addFile= async(Name,filePath)=> {
  const file=fs.readFileSync(filePath);
  const hashes = [];
  const filesAdded = ipfs.add({path: Name, content: file});
  for await (const result of filesAdded) {
    hashes.push(result.hash);
    console.log(result.hash);
    console.log(result);

  }

  return hashes; // if you know it's just one for example
};

It gave me an information of a file, but hash does not work as it gave me undefined, I want extract just a hash like this "QmRndAYkvH3D2qhmYfaAZvWT6MDi4NiJPbzJor3EL87rrb"

结果

Since ipfs.add() returns an async-iterable object, you need to use for async to go through it like this:

const addFile= async(Name,filePath)=> {
  const file=fs.readFileSync(filePath);
  const hashes = [];
  const filesAdded = ipfs.add({path: Name, content: file});
  for await (const result of filesAdded) {
    if (result.hash) {
      hashes.push(result.hash);
    } else if (result.cid) {
      hashes.push(result.cid.multihash); // guessing here - might be another part of the cid object
    } else {
      console.log("No hash found in",result);
    }
  }

  return hashes[0]; // if you know it's just one for example
};

You have to change this:

const fileHash = fileAdded[0].hash;

into this:

const fileHash = fileAdded.hash;

(so remove [0] ).

This worked for me: it has to do with the libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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