0

我似乎无法找出在我的快速应用程序 (/services/IPFS.js) 中运行 IPFS 节点的正确方法,同时也能够在我的路由 (/routes/uploads.js) 中访问它

/服务/IPFS.js

const IPFS = require("ipfs-core");

module.exports = startNode = async (req, res, next) => {
  console.log("Starting IPFS node...");
  return await IPFS.create();
};

index.js

const express = require("express");
const bodyParser = require("body-parser");
const apiRouter = require("./routes/api");
const cors = require("cors");
const app = express();
const port = 4000;
const startNode = require("./services/IPFS");

app.use(cors());

app.use(bodyParser.urlencoded());
app.use(bodyParser.json());

app.use("/api/v1", apiRouter);

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

startNode();

如何将我的 IPFS 实例传递给/routes/upload.js我以便ipfs.add(file)在我的/upload端点中使用?

任何帮助表示赞赏。

谢谢

4

1 回答 1

0

您可以将 定义apiRouter为工厂函数并将函数传递startNode给它。在您的路由器中,您可以call

// in your index.js
// ...
app.use("/api/v1", apiRouter(startNode));
// ...

// in your apiRouter.js
const express = require('express');
const router = express.Router();

module.exports = (startNodeFn) => {

    router.post('/upload', async (req, res) => {
       const result = await startNodeFn.call(startNodeFn, req, res);
       // handle result and do upload ...
    });

    // rest of routes
    // ...
    return router;
}
于 2020-12-09T10:55:34.940 回答