如何在.js文件中的app.post()内部定义函数

时间:2018-11-15 10:14:36

标签: javascript node.js

我运行nodeserver.js文件以启动项目的NodeJS应用程序。我想在我的angular(前端)上传文件后立即调用file-uploader.controller.js文件。 在这里,我认为我们可以在内部传递一个函数-

app.post("/upload", upload.array("uploads[]", 12), function (req, res) 
{
//code
}

controller.js是700行代码。所以我想要在一个单独的文件中。 请帮忙。

projectserver.js

// Server definitions

var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
const neo4j = require('neo4j-driver').v1;


var restify = require('restify');
var expressJwt = require('express-jwt');
var session = require('express-session');
var config = require('./config.json')
var app = express();
var router = express.Router();
module.exports = router;

app.use(restify.plugins.bodyParser());

app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());
// app.use(express.bodyParser());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))

app.use(cors());

app.use(session({ secret: config.secret, resave: false, saveUninitialized: true }));


// -----------------  File Uploader code   -------------------------

var express = require('express');
var multer = require('multer');
var path = require('path');
var app = express();
var mkdirp = require('mkdirp')
var port = 3003;

app.use(express.static(path.join(__dirname, 'uploads')));
// headers and content type
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});


var storage = multer.diskStorage({

    destination: function (req, file, cb) {

        var dir = './uploads/';
        mkdirp(dir, function (err) {
            if (err) {
                console.error(err);
            }
            // move cb to here
            cb(null, dir);
        });
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }

});
var upload = multer({ storage: storage });


app.post("/upload", upload.array("uploads[]", 12), function (req, res) {

    fileName = req.files[0].filename;

    console.log("global variable FileName = ", fileName)

    console.log('files', req.files);
    console.log("request filename = ",req.files[0].filename );
    res.send(req.files);
});


var server = app.listen(port, function () {
    console.log("Listening on port %s...", port);
});

file-uploader.controller.js

const express = require('express');
const yaml = require('js-yaml');
const app = express();
var router = express.Router();
const configFile = require('./config.json');
const port = 3000

var filename = fileName;



// --------------- File upload code till above  -------------------

var orgName = organization.toLowerCase();
var dep = department.toLowerCase();

var cypher0 = "CREATE (" + orgName + ":Organization {name:\"" + organization + "\"})";
var constraint = "CREATE CONSTRAINT ON (n:Organization) ASSERT n.name IS UNIQUE";


org = [cypher0, constraint];

const indentedJson = "";


const fs = require('fs');

app.get('/', (request, response) => {
    response.send("renewalQuote")
})

app.listen(port, (err) => {
    if (err) {
        return console.log('something bad happened', err)
    }
});


var config;
try {
    function safeLoader(callback) {

        config = yaml.safeLoad(fs.readFileSync(filename, 'utf8'));
        callback(config);
    }
    safeLoader(callback);




} catch (e) {
    console.log(e);
}


// more code

1 个答案:

答案 0 :(得分:0)

您可以在file-uploader.controller.js中导出一个类,然后在projectserver.js require中导出它并使用它。

一个简单的例子:

// file-uploader.controller.js

class uploader {
  async run() {
    // todo something
  }
}

// projectserver.js
const Uploader = require('./file-uploader.controller');
app.post("/upload", upload.array("uploads[]", 12), function (req, res) {
    await Uploader.run();
});