복붙노트

[NODEJS] Node.js를에서, 어떻게 내 다른 파일에서 함수를 "포함"합니까?

NODEJS

Node.js를에서, 어떻게 내 다른 파일에서 함수를 "포함"합니까?

해결법


  1. 1.당신은 당신이 당신이 노출 할 것을 선언 할 필요가 모든 JS 파일을 요구할 수 있습니다.

    당신은 당신이 당신이 노출 할 것을 선언 할 필요가 모든 JS 파일을 요구할 수 있습니다.

    // tools.js
    // ========
    module.exports = {
      foo: function () {
        // whatever
      },
      bar: function () {
        // whatever
      }
    };
    
    var zemba = function () {
    }
    

    그리고 앱 파일 :

    // app.js
    // ======
    var tools = require('./tools');
    console.log(typeof tools.foo); // => 'function'
    console.log(typeof tools.bar); // => 'function'
    console.log(typeof tools.zemba); // => undefined
    

  2. 2.모든 다른 답변에도 불구하고, 여전히 전통적으로 Node.js를 소스 파일에 파일을 포함 할 경우, 당신은이를 사용할 수 있습니다 :

    모든 다른 답변에도 불구하고, 여전히 전통적으로 Node.js를 소스 파일에 파일을 포함 할 경우, 당신은이를 사용할 수 있습니다 :

    var fs = require('fs');
    
    // file is included here:
    eval(fs.readFileSync('tools.js')+'');
    

    대부분의 경우이 나쁜 관행이라는 점에 유의하고 대신 모듈을 작성해야 바랍니다. 그러나 해당 지역의 환경 / 공간의 오염은 당신이 정말로 원하는 것입니다 드문 경우가 있습니다.

    또한 "엄격한 사용"이하지 않습니다 작업을 유의하시기 바랍니다; (당신이 "엄격 모드"에있을 때)은 "수입"파일에 정의 된 함수와 변수는 가져 오기를 수행하는 코드에 액세스 할 수 없습니다 때문입니다. 엄격한 모드는 언어 표준의 최신 버전에 의해 정의 된 몇 가지 규칙을 적용합니다. 이 여기에 설명 된 솔루션을 방지하는 또 다른 이유가 될 수 있습니다.


  3. 3.당신은 새로운 기능이나 새로운 모듈을 필요가 없습니다. 당신이 네임 스페이스를 사용하지 않으려면 당신은 단순히 당신이 전화하는거야 모듈을 실행해야합니다.

    당신은 새로운 기능이나 새로운 모듈을 필요가 없습니다. 당신이 네임 스페이스를 사용하지 않으려면 당신은 단순히 당신이 전화하는거야 모듈을 실행해야합니다.

    module.exports = function() { 
        this.sum = function(a,b) { return a+b };
        this.multiply = function(a,b) { return a*b };
        //etc
    }
    

    또는 myController.js 같은 기타의 .js에서 :

    대신에

    VAR 도구 = tools.sum 같은 네임 스페이스와 전화 도구 (1, 2)를 사용하여 우리를 강제로 ( 'tools.js')을 필요로;

    우리는 간단하게 호출 할 수 있습니다

    require('tools.js')();
    

    그리고

    sum(1,2);
    

    내 경우에는 내가 컨트롤러 ctrls.js을 가진 파일이

    module.exports = function() {
        this.Categories = require('categories.js');
    }
    

    공용 클래스 후 ( 'ctrls.js')을 필요로하고 내가) (모든 상황에서 카테고리를 사용할 수 있습니다


  4. 4.이 개 JS 파일 만들기

    이 개 JS 파일 만들기

    // File cal.js
    module.exports = {
        sum: function(a,b) {
            return a+b
        },
        multiply: function(a,b) {
            return a*b
        }
    };
    

    홈페이지 JS 파일

    // File app.js
    var tools = require("./cal.js");
    var value = tools.sum(10,20);
    console.log("Value: "+value);
    

    콘솔 출력

    Value: 30
    

  5. 5.두 개의 파일 예 : app.js 및 tools.js를 만들

    두 개의 파일 예 : app.js 및 tools.js를 만들

    app.js

    const tools= require("./tools.js")
    
    
    var x = tools.add(4,2) ;
    
    var y = tools.subtract(4,2);
    
    
    console.log(x);
    console.log(y);
    

    tools.js

     const add = function(x, y){
            return x+y;
        }
     const subtract = function(x, y){
                return x-y;
        }
    
        module.exports ={
            add,subtract
        }
    

    산출

    6
    2
    

  6. 6.여기 평범하고 간단한 설명입니다 :

    여기 평범하고 간단한 설명입니다 :

    // Include the public functions from 'helpers.js'
    var helpers = require('./helpers');
    
    // Let's assume this is the data which comes from the database or somewhere else
    var databaseName = 'Walter';
    var databaseSurname = 'Heisenberg';
    
    // Use the function from 'helpers.js' in the main file, which is server.js
    var fullname = helpers.concatenateNames(databaseName, databaseSurname);
    
    // 'module.exports' is a node.JS specific feature, it does not work with regular JavaScript
    module.exports = 
    {
      // This is the function which will be called in the main file, which is server.js
      // The parameters 'name' and 'surname' will be provided inside the function
      // when the function is called in the main file.
      // Example: concatenameNames('John,'Doe');
      concatenateNames: function (name, surname) 
      {
         var wholeName = name + " " + surname;
    
         return wholeName;
      },
    
      sampleFunctionTwo: function () 
      {
    
      }
    };
    
    // Private variables and functions which will not be accessible outside this file
    var privateFunction = function () 
    {
    };
    

  7. 7.https://stackoverflow.com/a/8744519/2979590를 메시지가 표시 - NodeJS이 기능을 '포함'나는 우도 G에 의해 제안 된 솔루션을 확인하기위한 나는 또한 찾고 있었다. 그의 코드는 내 포함 된 JS 파일을 작동하지 않습니다. 마지막으로 그와 같은 문제를 해결 :

    https://stackoverflow.com/a/8744519/2979590를 메시지가 표시 - NodeJS이 기능을 '포함'나는 우도 G에 의해 제안 된 솔루션을 확인하기위한 나는 또한 찾고 있었다. 그의 코드는 내 포함 된 JS 파일을 작동하지 않습니다. 마지막으로 그와 같은 문제를 해결 :

    var fs = require("fs");
    
    function read(f) {
      return fs.readFileSync(f).toString();
    }
    function include(f) {
      eval.apply(global, [read(f)]);
    }
    
    include('somefile_with_some_declarations.js');
    

    물론, 그 도움이됩니다.


  8. 8.말을 우리는 lib.js 파일에있는 기능 핑 ()를 호출하고 (30,20)를 추가하고 싶어 main.js에서

    말을 우리는 lib.js 파일에있는 기능 핑 ()를 호출하고 (30,20)를 추가하고 싶어 main.js에서

    main.js

    lib = require("./lib.js")
    
    output = lib.ping();
    console.log(output);
    
    //Passing Parameters
    console.log("Sum of A and B = " + lib.add(20,30))
    

    lib.js

    this.ping=function ()
    {
        return  "Ping Success"
    }
    
    //Functions with parameters
    this.add=function(a,b)
        {
            return a+b
        }
    

  9. 9.Node.js를 VM에서 모듈 (세계 객체를 포함한) 현재의 컨텍스트 내에 자바 스크립트 코드를 실행할 수있는 기능을 제공한다. http://nodejs.org/docs/latest/api/vm.html#vm_vm_runinthiscontext_code_filename 참조

    Node.js를 VM에서 모듈 (세계 객체를 포함한) 현재의 컨텍스트 내에 자바 스크립트 코드를 실행할 수있는 기능을 제공한다. http://nodejs.org/docs/latest/api/vm.html#vm_vm_runinthiscontext_code_filename 참조

    참고 오늘 같이 VM 모듈에 버그가있을 것으로 prevenst runInThisContext이 새로운 컨텍스트에서 호출 할 때 권리를하고부터. 주요 프로그램은 코드가 runInThisContext를 호출하는 다음 새로운 컨텍스트 내에서 코드를 실행하고있는 경우에만 문제. https://github.com/joyent/node/issues/898 참조

    슬프게도, 페르난도 제안 있음 (글로벌) 접근 않는 등의 이름이 기능하지 작업 "함수 foo () {}"로

    즉, 여기에 나를 위해 작동하는지 인클루드 () 함수는 다음과 같습니다

    function include(path) {
        var code = fs.readFileSync(path, 'utf-8');
        vm.runInThisContext(code, path);
    }
    

  10. 10.우도 G.는 말했다 :

    우도 G.는 말했다 :

    그는 바로,하지만 함수에서 전역 범위에 영향을 미칠 수있는 방법이있다. 자신의 예를 개선 :

    function include(file_) {
        with (global) {
            eval(fs.readFileSync(file_) + '');
        };
    };
    
    include('somefile_with_some_declarations.js');
    
    // the declarations are now accessible here.
    

    희망은 그 도움이됩니다.


  11. 11.그것은 .... 다음과 같이 나와 함께 일했다

    그것은 .... 다음과 같이 나와 함께 일했다

    Lib1.js

    //Any other private code here 
    
    // Code you want to export
    exports.function1 = function(params) {.......};
    exports.function2 = function(params) {.......};
    
    // Again any private code
    

    이제 Main.js 파일에 당신은 Lib1.js을 포함해야

    var mylib = requires('lib1.js');
    mylib.function1(params);
    mylib.function2(params);
    

    node_modules 폴더에 Lib1.js을 넣어 기억하십시오.


  12. 12.당신은 글로벌 변수에 함수를 넣을 수 있지만, 그냥 모듈로 도구 스크립트를 설정하는 더 좋습니다. 그것은 너무 열심히 정말 아니에요 - 바로 수출 객체에 공개 API를 연결합니다. 좀 더 세부 사항에 대한 이해 Node.js를 '수출 모듈을 살펴보십시오.

    당신은 글로벌 변수에 함수를 넣을 수 있지만, 그냥 모듈로 도구 스크립트를 설정하는 더 좋습니다. 그것은 너무 열심히 정말 아니에요 - 바로 수출 객체에 공개 API를 연결합니다. 좀 더 세부 사항에 대한 이해 Node.js를 '수출 모듈을 살펴보십시오.


  13. 13.내 의견으로는이 작업을 수행하는 또 다른 방법은, 당신이 필요로 호출 할 때 LIB 파일에 모든 것을 실행하는 것입니다 () 함수를 사용하여 (기능 (여기에 / * 일 * /) {}) (); 이 정확히 평가처럼, 전역 이러한 모든 기능을 할 것이다 일을 () 솔루션

    내 의견으로는이 작업을 수행하는 또 다른 방법은, 당신이 필요로 호출 할 때 LIB 파일에 모든 것을 실행하는 것입니다 () 함수를 사용하여 (기능 (여기에 / * 일 * /) {}) (); 이 정확히 평가처럼, 전역 이러한 모든 기능을 할 것이다 일을 () 솔루션

    SRC / lib.js

    (function () {
        funcOne = function() {
                console.log('mlt funcOne here');
        }
    
        funcThree = function(firstName) {
                console.log(firstName, 'calls funcThree here');
        }
    
        name = "Mulatinho";
        myobject = {
                title: 'Node.JS is cool',
                funcFour: function() {
                        return console.log('internal funcFour() called here');
                }
        }
    })();
    

    그리고 당신의 주요 코드는 같은 이름으로 함수를 호출 할 수 있습니다 :

    main.js

    require('./src/lib')
    funcOne();
    funcThree('Alex');
    console.log(name);
    console.log(myobject);
    console.log(myobject.funcFour());
    

    이 출력을 만들 것

    bash-3.2$ node -v
    v7.2.1
    bash-3.2$ node main.js 
    mlt funcOne here
    Alex calls funcThree here
    Mulatinho
    { title: 'Node.JS is cool', funcFour: [Function: funcFour] }
    internal funcFour() called here
    undefined
    

    당신이 내 object.func를 호출 할 때 정의되지 않은에주의하십시오 ()는 평가와 함께로드하는 경우, 그것은 동일합니다 (). 희망이 도움이 :)


  14. 14.난 그냥 다음 버전 6.4 이후 Node.js를 지원하는 destructuring 할당을 사용할 수 있으며, 경우에 당신이 당신의 tools.js에서 수입 단지 특정 기능을 필요, 추가 할 - node.green를 참조하십시오.

    난 그냥 다음 버전 6.4 이후 Node.js를 지원하는 destructuring 할당을 사용할 수 있으며, 경우에 당신이 당신의 tools.js에서 수입 단지 특정 기능을 필요, 추가 할 - node.green를 참조하십시오.

    예: (두 파일은 같은 폴더에 있습니다)

    module.exports = {
        sum: function(a,b) {
            return a + b;
        },
        isEven: function(a) {
            return a % 2 == 0;
        }
    };
    
    const { isEven } = require('./tools.js');
    
    console.log(isEven(10));
    

    출력 : 사실

    이것은 또한 다음 (공통) 과제에서의 경우와 다른 개체의 속성으로 이러한 기능을 할당하는 것이 방지 :

    CONST 도구 = 필요 ( './ tools.js');

    당신은 tools.isEven (10)를 호출해야하는 경우.

    노트:

    올바른 경로와 파일 이름을 접두사 것을 잊지 마세요 - 두 파일이 동일한 폴더에있는 경우에도 필요에 접두어 ./

    Node.js를 워드 프로세서에서 :


  15. 15.app.js

    app.js

    let { func_name } = require('path_to_tools.js');
    func_name();    //function calling
    

    tools.js

    let func_name = function() {
        ...
        //function body
        ...
    };
    
    module.exports = { func_name };
    

  16. 16.두 개의 파일 예 : app.js 및 standard_funcs.js를 만들

    두 개의 파일 예 : app.js 및 standard_funcs.js를 만들

    standard_funcs.js

    // Declaration
    
     module.exports =
       {
            add,
            subtract
            // ...
        }
    
    
    // Implementation
    
     function add(x, y){
            return x+y;
        }
    
     function subtract(x, y){
                return x-y;
        }
        
    

    app.js

    // include
    
    const sf= require("./standard_funcs.js")
    
    // use
    
    var x = sf.add(4,2) ;
    
    var y = sf.subtract(4,2);
    
    
    console.log(x);
    console.log(y);
    
        
    

    산출

    6
    2
    

  17. 17.

    define({
        "data": "XYZ"
    });
    
    var fs = require("fs");
    var vm = require("vm");
    
    function include(path, context) {
        var code = fs.readFileSync(path, 'utf-8');
        vm.runInContext(code, vm.createContext(context));
    }
    
    
    // Include file
    
    var customContext = {
        "define": function (data) {
            console.log(data);
        }
    };
    include('./fileToInclude.js', customContext);
    

  18. 18.이것은 내가 지금까지 만든 가장 좋은 방법입니다.

    이것은 내가 지금까지 만든 가장 좋은 방법입니다.

    var fs = require('fs'),
        includedFiles_ = {};
    
    global.include = function (fileName) {
      var sys = require('sys');
      sys.puts('Loading file: ' + fileName);
      var ev = require(fileName);
      for (var prop in ev) {
        global[prop] = ev[prop];
      }
      includedFiles_[fileName] = true;
    };
    
    global.includeOnce = function (fileName) {
      if (!includedFiles_[fileName]) {
        include(fileName);
      }
    };
    
    global.includeFolderOnce = function (folder) {
      var file, fileName,
          sys = require('sys'),
          files = fs.readdirSync(folder);
    
      var getFileName = function(str) {
            var splited = str.split('.');
            splited.pop();
            return splited.join('.');
          },
          getExtension = function(str) {
            var splited = str.split('.');
            return splited[splited.length - 1];
          };
    
      for (var i = 0; i < files.length; i++) {
        file = files[i];
        if (getExtension(file) === 'js') {
          fileName = getFileName(file);
          try {
            includeOnce(folder + '/' + file);
          } catch (err) {
            // if (ext.vars) {
            //   console.log(ext.vars.dump(err));
            // } else {
            sys.puts(err);
            // }
          }
        }
      }
    };
    
    includeFolderOnce('./extensions');
    includeOnce('./bin/Lara.js');
    
    var lara = new Lara();
    

    당신은 여전히 ​​내보낼 것을 알릴 필요

    includeOnce('./bin/WebServer.js');
    
    function Lara() {
      this.webServer = new WebServer();
      this.webServer.start();
    }
    
    Lara.prototype.webServer = null;
    
    module.exports.Lara = Lara;
    

  19. 19.나뿐만 아니라, 쓰기 모듈없이 인공 호흡기를 코드를 포함하는 옵션을 찾고 있었다. Node.js를 서비스에 대한 서로 다른 프로젝트에서 동일한 테스트를 독립 소스를 사용 - 그리고 jmparattes의 대답은 나를 위해 그것을했다.

    나뿐만 아니라, 쓰기 모듈없이 인공 호흡기를 코드를 포함하는 옵션을 찾고 있었다. Node.js를 서비스에 대한 서로 다른 프로젝트에서 동일한 테스트를 독립 소스를 사용 - 그리고 jmparattes의 대답은 나를 위해 그것을했다.

    이점은 내가 "엄격한 사용"에 문제가없는, 네임 스페이스를 오염하지 않는,이다; 그것은 잘 작동합니다.

    전체 샘플 여기 :

    "use strict";
    
    (function(){
    
        var Foo = function(e){
            this.foo = e;
        }
    
        Foo.prototype.x = 1;
    
        return Foo;
    
    }())
    
    "use strict";
    
    const fs = require('fs');
    const path = require('path');
    
    var SampleModule = module.exports = {
    
        instAFoo: function(){
            var Foo = eval.apply(
                this, [fs.readFileSync(path.join(__dirname, '/lib/foo.js')).toString()]
            );
            var instance = new Foo('bar');
            console.log(instance.foo); // 'bar'
            console.log(instance.x); // '1'
        }
    
    }
    

    이 어떻게 든 도움이되었습니다 바랍니다.


  20. 20.당신은 파일 abc.txt 및 더 많은 데처럼?

    당신은 파일 abc.txt 및 더 많은 데처럼?

    이 개 파일을 만듭니다 fileread.js 및 fetchingfile.js는 다음 fileread.js이 코드를 작성 :

    function fileread(filename) {
        var contents= fs.readFileSync(filename);
            return contents;
        }
    
        var fs = require("fs");  // file system
    
        //var data = fileread("abc.txt");
        module.exports.fileread = fileread;
        //data.say();
        //console.log(data.toString());
    }
    

    fetchingfile.js에서이 코드를 작성 :

    function myerror(){
        console.log("Hey need some help");
        console.log("type file=abc.txt");
    }
    
    var ags = require("minimist")(process.argv.slice(2), { string: "file" });
    if(ags.help || !ags.file) {
        myerror();
        process.exit(1);
    }
    var hello = require("./fileread.js");
    var data = hello.fileread(ags.file);  // importing module here 
    console.log(data.toString());
    

    이제 터미널에서 : $ 노드 fetchingfile.js --file = abc.txt

    당신은 또한 그것을 전달하는 대신 readfile.js에있는 모든 파일을 포함, 인수로 파일 이름을 전달한다.

    감사


  21. 21.또 다른 방법 때 Node.js를하고 express.js 프레임 워크를 사용하여

    또 다른 방법 때 Node.js를하고 express.js 프레임 워크를 사용하여

    var f1 = function(){
       console.log("f1");
    }
    var f2 = function(){
       console.log("f2");
    }
    
    module.exports = {
       f1 : f1,
       f2 : f2
    }
    

    S라는 이름의 js 파일 및 폴더 통계이 저장

    이제 기능을 사용하는 방법

    var s = require('../statics/s');
    s.f1();
    s.f2();
    

  22. 22.당신은 간단한은 ( './ 파일 이름')를 요구할 수 있습니다.

    당신은 간단한은 ( './ 파일 이름')를 요구할 수 있습니다.

    예.

    // file: index.js
    var express = require('express');
    var app = express();
    var child = require('./child');
    app.use('/child', child);
    app.get('/', function (req, res) {
      res.send('parent');
    });
    app.listen(process.env.PORT, function () {
      console.log('Example app listening on port '+process.env.PORT+'!');
    });
    
    // file: child.js
    var express = require('express'),
    child = express.Router();
    console.log('child');
    child.get('/child', function(req, res){
      res.send('Child2');
    });
    child.get('/', function(req, res){
      res.send('Child');
    });
    
    module.exports = child;
    

    점에 유의하시기 바랍니다:


  23. 23.나는 HTML 템플릿에 대해이 작업을 처리하는 대신 원유 방법을 마련했습니다. ? 마찬가지로 PHP에게

    나는 HTML 템플릿에 대해이 작업을 처리하는 대신 원유 방법을 마련했습니다. ? 마찬가지로 PHP에게

    var fs = require('fs');
    
    String.prototype.filter = function(search,replace){
        var regex = new RegExp("{{" + search.toUpperCase() + "}}","ig");
        return this.replace(regex,replace);
    }
    
    var navigation = fs.readFileSync(__dirname + "/parts/navigation.html");
    
    function preProcessPage(html){
        return html.filter("nav",navigation);
    }
    
    var express = require('express');
    var app = express();
    // Keep your server directory safe.
    app.use(express.static(__dirname + '/public/'));
    // Sorta a server-side .htaccess call I suppose.
    app.get("/page_name/",function(req,res){
        var html = fs.readFileSync(__dirname + "/pages/page_name.html");
        res.send(preProcessPage(html));
    });
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>NodeJS Templated Page</title>
        <link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="/css/font-awesome.min.css">
        <!-- Scripts Load After Page -->
        <script type="text/javascript" src="/js/jquery.min.js"></script>
        <script type="text/javascript" src="/js/tether.min.js"></script>
        <script type="text/javascript" src="/js/bootstrap.min.js"></script>
    </head>
    <body>
        {{NAV}}
        <!-- Page Specific Content Below Here-->
    </body>
    </html>
    
    <nav></nav>
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>NodeJS Templated Page</title>
        <link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="/css/font-awesome.min.css">
        <!-- Scripts Load After Page -->
        <script type="text/javascript" src="/js/jquery.min.js"></script>
        <script type="text/javascript" src="/js/tether.min.js"></script>
        <script type="text/javascript" src="/js/bootstrap.min.js"></script>
    </head>
    <body>
        <nav></nav>
        <!-- Page Specific Content Below Here-->
    </body>
    </html>
    

  24. 24.당신이 속도 일까지로, 다수의 CPU 및 Microservice 아키텍처를 원하신다면 ... 사용 된 RPC를 통해 프로세스를 포크.

    당신이 속도 일까지로, 다수의 CPU 및 Microservice 아키텍처를 원하신다면 ... 사용 된 RPC를 통해 프로세스를 포크.

    복잡한 소리, 그러나 그것의 간단한 당신이 문어를 사용하는 경우.

    다음은 그 예이다 :

    tools.js에 추가 :

    const octopus = require('octopus');
    var rpc = new octopus('tools:tool1');
    
    rpc.over(process, 'processRemote');
    
    var sum = rpc.command('sum'); // This is the example tool.js function to make available in app.js
    
    sum.provide(function (data) { // This is the function body
        return data.a + data.b;
    });
    

    app.js에 추가 :

    const { fork } = require('child_process');
    const octopus = require('octopus');
    const toolprocess = fork('tools.js');
    
    var rpc = new octopus('parent:parent1');
    rpc.over(toolprocess, 'processRemote');
    
    var sum = rpc.command('sum');
    
    // Calling the tool.js sum function from app.js
    sum.call('tools:*', {
        a:2, 
        b:3
    })
    .then((res)=>console.log('response : ',rpc.parseResponses(res)[0].response));
    

    공개 - 나는 문어의 저자, ​​그리고 내가 어떤 경량 라이브러리를 찾을 수 없기 때문에, 내 유사한 사용 사례에 대한 경우 내장.


  25. 25.모듈에 "도구"를 설정하려면, 나는 모든 열심히 볼 수 없습니다. 모든 다른 답변에도 불구하고 나는 여전히 module.exports의 사용을 권장합니다 :

    모듈에 "도구"를 설정하려면, 나는 모든 열심히 볼 수 없습니다. 모든 다른 답변에도 불구하고 나는 여전히 module.exports의 사용을 권장합니다 :

    //util.js
    module.exports = {
       myFunction: function () {
       // your logic in here
       let message = "I am message from myFunction";
       return message; 
      }
    }
    

    이제 우리는 (| 색인 | 앱에서 server.js) 전역이 수출을 할당해야

    var util = require('./util');
    

    지금 당신은 참조 및 통화 기능과 같은 수 있습니다 :

    //util.myFunction();
    console.log(util.myFunction()); // prints in console :I am message from myFunction 
    

  26. 26.사용하다:

    사용하다:

    var mymodule = require("./tools.js")
    

    app.js :

    module.exports.<your function> = function () {
        <what should the function do>
    }
    
  27. from https://stackoverflow.com/questions/5797852/in-node-js-how-do-i-include-functions-from-my-other-files by cc-by-sa and MIT license