我正在尝试将在server.js文件中创建的grid-fs实例导出到api目录中的路由。 如果我将所有路由都放入server.js文件,则该代码有效,但如果我将代码移至其他文件夹,则该代码不起作用。
我尝试从server.js导出gfs实例,并在api文件夹中的logs.js中要求它,但是gfs似乎是logs.js文件中的空对象。
//Server.js file
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const fs = require("fs");
const unzipper = require("unzipper");
const streamZip = require("node-stream-zip");
// file upload
const GridFsStorage = require("multer-gridfs-storage");
const Grid = require("gridfs-stream");
const multer = require("multer");
//import routes
const logs = require("./routes/api/logs");
const mongoURI = require("./config/keys/keys").mongoURI;
const storage = new GridFsStorage({
url: "MY_URL",
file: (req, file) => {
console.log(file);
return new Promise((resolve, reject) => {
const filename = `${new Date()
.toJSON()
.slice(0, 10)
.split("-")
.reverse()
.join(".")} - ${file.originalname}`;
const fileInfo = {
filename,
bucketName: "uploads"
};
resolve(fileInfo);
});
}
});
const upload = multer({
storage,
fileFilter: function(req, file, cb) {
var filetypes = /zip/;
// var filetypes = /json|csv/;
// var mimetype = filetypes.test(file.mimetype);
var extname = filetypes.test(path.extname(file.originalname).toLowerCase());
if (extname) {
return cb(null, true);
}
cb({
fileTypeError:
"File upload only supports the following filetypes - " + filetypes
});
}
}).single("file");
const mongoose = require("mongoose");
const cors = require("cors");
// create mongo connection
const conn = mongoose.createConnection(mongoURI);
conn.on("error", err => {
if (err) {
console.log(err);
}
});
const app = express();
// Init gfs
let gfs;
conn.once("open", () => {
console.log("connection open");
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection("uploads");
});
app.use(bodyParser.json({ limit: "50mb" }));
app.use(
bodyParser.urlencoded({
extended: true,
limit: "50mb",
parameterLimit: 1000000
})
);
app.use(cors());
//use routes
//todo: WE WANT TO ACCESS gfs instance in this route
app.use("/", logs);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
//I HAVE TRIED EXPORTING IT THIS WAY
module.exports = gfs;
//in logs.js file
const express = require("express");
const Router = express.Router();
const gfs = require("../../server");
// @route GET api/logs/files
// @desc Display all files in JSON
Router.get("/api/logs/files", (req, res) => {
//send back error if db is not connected
if (!gfs) {
return res.status(503).json({ error: "No internet connection" });
}
gfs.files
.find()
.sort({ uploadDate: -1 })
.toArray((err, files) => {
if (!files || (Array.isArray(files) && files.length === 0)) {
return res.status(404).json({
error: `Files not found`
});
}
if (err) {
return res.status(503).json({ error: "Error while loading files " });
}
return res.json(files);
});
});
module.exports = Router;
//ERROR: Cannot read find of undefined.
// gfs is emprt object in logs.js file