简体   繁体   中英

NodeJS - how can I make my code beautiful / cleaner / better readable

I have generated my app with express --view=pug myapp which created me a folder-tree with the files I need to start over.. I wrote some code which I would like to outsource from the main app.js in maybe a function-file or something like that, to keep the app.js cleaner.

where would I put my custom functions? how would I then require the function-file in nodeJS ?

You can arrange your files as you wish. Wherever you keep your functions, just add the functions you want to use in any other files to module.exports object in that file. Then in your app.js (or any other file where you want to use these functions), import the file using require and you should have access to all the exported properties and functions from the file you import.

For example:

I can put my functions in ./lib/core-lib.js:

function test(){
  // do something
}

module.exports = {
  test: test
};

And then in my app.js

const lib = require('./lib/core-lib');


lib.test();

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