How to define a function inside an app.post() in .js file










0















I run my nodeserver.js file to start NodeJS application of my project. I want to invoke file-uploader.controller.js file as soon as the my angular (front-end ) uploads a file.
Here i think we can pass a function inside -



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

//code



controller.js is a 700 line code. So i want it in a separate file.
Please help.



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









share|improve this question
























  • Thanks. I found out the answer. I followed here - stackoverflow.com/questions/34920933/…

    – Techdive
    Nov 15 '18 at 12:01















0















I run my nodeserver.js file to start NodeJS application of my project. I want to invoke file-uploader.controller.js file as soon as the my angular (front-end ) uploads a file.
Here i think we can pass a function inside -



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

//code



controller.js is a 700 line code. So i want it in a separate file.
Please help.



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









share|improve this question
























  • Thanks. I found out the answer. I followed here - stackoverflow.com/questions/34920933/…

    – Techdive
    Nov 15 '18 at 12:01













0












0








0








I run my nodeserver.js file to start NodeJS application of my project. I want to invoke file-uploader.controller.js file as soon as the my angular (front-end ) uploads a file.
Here i think we can pass a function inside -



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

//code



controller.js is a 700 line code. So i want it in a separate file.
Please help.



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









share|improve this question
















I run my nodeserver.js file to start NodeJS application of my project. I want to invoke file-uploader.controller.js file as soon as the my angular (front-end ) uploads a file.
Here i think we can pass a function inside -



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

//code



controller.js is a 700 line code. So i want it in a separate file.
Please help.



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






javascript node.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 10:35







Techdive

















asked Nov 15 '18 at 10:14









TechdiveTechdive

22917




22917












  • Thanks. I found out the answer. I followed here - stackoverflow.com/questions/34920933/…

    – Techdive
    Nov 15 '18 at 12:01

















  • Thanks. I found out the answer. I followed here - stackoverflow.com/questions/34920933/…

    – Techdive
    Nov 15 '18 at 12:01
















Thanks. I found out the answer. I followed here - stackoverflow.com/questions/34920933/…

– Techdive
Nov 15 '18 at 12:01





Thanks. I found out the answer. I followed here - stackoverflow.com/questions/34920933/…

– Techdive
Nov 15 '18 at 12:01












1 Answer
1






active

oldest

votes


















0














You can export a class in file-uploader.controller.js, and then, in projectserver.js require it, and use it.



A simple example:



// 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();
);





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53317082%2fhow-to-define-a-function-inside-an-app-post-in-js-file%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You can export a class in file-uploader.controller.js, and then, in projectserver.js require it, and use it.



    A simple example:



    // 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();
    );





    share|improve this answer





























      0














      You can export a class in file-uploader.controller.js, and then, in projectserver.js require it, and use it.



      A simple example:



      // 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();
      );





      share|improve this answer



























        0












        0








        0







        You can export a class in file-uploader.controller.js, and then, in projectserver.js require it, and use it.



        A simple example:



        // 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();
        );





        share|improve this answer















        You can export a class in file-uploader.controller.js, and then, in projectserver.js require it, and use it.



        A simple example:



        // 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();
        );






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 15 '18 at 11:50









        bcperth

        2,0351614




        2,0351614










        answered Nov 15 '18 at 11:10









        whyourwhyour

        113




        113





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53317082%2fhow-to-define-a-function-inside-an-app-post-in-js-file%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

            Museum of Modern and Contemporary Art of Trento and Rovereto