Node.js에서 다른 파일의 기능을 어떻게 "포함"합니까?


967

app.js라는 파일이 있다고 가정 해 봅시다. 아주 간단합니다 :

var express = require('express');
var app = express.createServer();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(req, res){
  res.render('index', {locals: {
    title: 'NowJS + Express Example'
  }});
});

app.listen(8080);

"tools.js"안에 함수가 있으면 어떻게 되나요? apps.js에서 사용하기 위해 어떻게 가져 옵니까?

아니면 ... "도구"를 모듈로 바꿔야합니까? << 어렵습니다. 오히려 tools.js 파일의 기본 가져 오기를 수행합니다.


4
여기서 나를 버린 것은 requireWindows의 동일한 디렉토리에있는 폴더를 사용하는 것이 었습니다 . ./mydir평범한 old 대신 유닉스 스타일 주소 지정을 사용해야 mydir합니다.
— Ben

1
스크립트를 가져오고, 파일로 내보내고, 외부 node_modules폴더 에서 모듈을 포함하는 모듈을 만들었습니다 . npmjs.com/package/node-import 도움이 되길 바랍니다. 감사!
— Nanang Mahdaen El-Agung 23 '54

답변:


1414

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

101
+1 훌륭하게, 가져온 코드를 자체 네임 스페이스로 제한합니다. 나중에 이것을 기록해 두어야합니다.
— Evan Plaice

8
외부 스크립트를 가져올 수 있는지 궁금합니다. require("http://javascript-modules.googlecode.com/svn/functionChecker.js")모듈을 올바르게 가져 오지 못하는 것 같습니다. 외부 스크립트를 가져 오는 다른 방법이 있습니까?
— 앤더슨 그린

6
그리고 변수에 함수에 변수를 전달해야한다면 어떻게해야합니까? bar : function (a, b) {// 일부 코드}
— Nishutosh Sharma

5
속성을 노출하기 때문에 module.exports 대신 내보내기를 사용합니다. 수출 대 module.exports : stackoverflow.com/questions/5311334/…
— Farm

4
foo () 함수 내에서 함수 bar ()를 호출하는 방법은 한 함수에서 다른 함수로 액세스하는 방법을 의미합니다
— pitu

303

다른 모든 답변에도 불구하고 여전히 전통적 으로 node.js 소스 파일에 파일을 포함 하려는 경우 다음을 사용할 수 있습니다.

var fs = require('fs');

// file is included here:
eval(fs.readFileSync('tools.js')+'');
  • +''파일 내용을 객체가 아닌 문자열로 가져 오려면 빈 문자열 연결 이 필요합니다 ( .toString()원하는 경우 에도 사용할 수 있음 ).
  • eval ()은 함수 내에서 사용될 수 없으며 전역 범위 내에서 호출 되어야합니다. 그렇지 않으면 함수 나 변수에 액세스 할 수 없습니다 (예 : include()유틸리티 함수 또는 이와 유사한 것을 만들 수 없음 ).

대부분의 경우 이것은 나쁜 습관 이므로 대신 모듈을 작성 해야 합니다 . 그러나 로컬 컨텍스트 / 네임 스페이스의 오염이 실제로 원하는 경우는 거의 없습니다.

2015-08-06 업데이트

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


41
쿨, 이것은 노드 스타일 포크를 유지할 필요없이 클라이언트 측을 위해 설계된 JS 라이브러리를 node.js 앱에 빠르게 배치하는 데 유용합니다.
— Kos

18
방금 모듈을 작성하지 않고 코드를 포함하는 것에 관한 원래 질문에 대답했습니다. 전자 는 특정 상황에서 이점을 가질 수 있습니다. 또한 require에 대한 가정이 잘못되었습니다. 코드는 확실히 평가되었지만 자체 네임 스페이스에 남아 있으며 호출 컨텍스트의 네임 스페이스를 "폴링"할 방법이 없으므로 직접 eval ()해야합니다. 대부분의 경우 anwer에 설명 된 방법을 사용하는 것은 나쁜 습관 이지만 TIMEX에 대한 것인지 결정 해야하는 것은 아닙니다.
— Udo G

14
@EvanPlaice : 실제로 질문에 대한 더 나은 제안 이 있습니까? 모듈이 아닌 파일을 포함해야하는 경우 이보다 더 나은 방법이 있습니까?
— jalf

8
때로는 포함해야 할 때가 있으며 때로는 대부분의 프로그래밍 언어에서 근본적으로 다른 두 가지 개념 인 Node JS도 있습니다. js를 제자리에 포함시키는 기능은 정직한 Node의 일부 여야하지만이를 평가하는 것은 본질적으로 괜찮은 해결책입니다. 공감.
— J. Martin

4
와 호환되지 않는 참고 엄격한 사용 으로 - 엄격한 사용 등의 평가를 통해 새로운 변수를 도입, 차단하여 평가의 사용을 제한합니다
— 팀보을

189

새로운 기능이나 새로운 모듈이 필요하지 않습니다. 네임 스페이스를 사용하지 않으려면 호출하는 모듈을 실행하면됩니다.

tools.js에서

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

app.js에서

또는 myController.js와 같은 다른 .js :

대신에

var tools = require('tools.js') 네임 스페이스를 사용하고 다음과 같은 도구를 호출해야합니다. tools.sum(1,2);

우리는 단순히 전화 할 수 있습니다

require('tools.js')();

그리고

sum(1,2);

내 경우에는 컨트롤러 ctrls.js 가있는 파일이 있습니다.

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

그리고 나는 Categories모든 상황에서 공개 수업으로 사용할 수 있습니다 .require('ctrls.js')()


12
+1이 더 이상 없나요? 이것은 질문이 묻는 것에 대한 진정한 해결책입니다 ( '공식적인'것은 아니지만). 노드가 정의되지 않은 대신 실제 파일을 가리키는 대신 유용한 호출 스택을 제공 할 수 있기 때문에 eval ()보다 디버깅이 백만 배 더 쉽습니다.
— user3413723

5
가져온 모듈에서는 "엄격한"모드를 사용할 수 없습니다.
— David

1
@Nick Panov : 훌륭합니다! this함수가 함수가 직접 호출 될 때 전역 범위 이기 때문에 작동한다는 점에 유의해야합니다 (어떤 방식으로도 바인딩되지 않음).
— Udo G

3
이것은 단지 내 인생을 바꾸었고 농담은 없었습니다 .1000 가지 이상의 라인 파일이 있었기 때문에 서로 다른 메소드의 변수가 서로 상관 관계가 있고 요구 사항이 모두 같은 범위에 require('blah.js')();있어야 하기 때문에 분해 할 수 없었습니다 ... 모두 같은 범위로 가져올 수 있습니다 !!! 감사!!!
— 샘 존슨

2
이것은 좋은 팁입니다! 주의 사항 : 표준 function () {} 선언이 아닌 () => {} 바로 가기 구문을 사용하여 module.exports 함수를 선언하면 실패합니다. 문제가 어디에 있는지 알아 내기 위해 한 시간을 걸렸습니다! (화살표 함수에는 자체 'this'속성이 없습니다 : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… )
— Ryan Griggs

117

두 개의 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

어떤 버전의 js가 작동합니까?
— Mirv-Matt

39

다음은 명확하고 간단한 설명입니다.

Server.js 컨텐츠 :

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

helpers.js 컨텐츠 :

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

34

또한 NodeJS 'include'기능을 찾고 있었고 Udo G가 제안한 솔루션을 확인했습니다-https://stackoverflow.com/a/8744519/2979590 메시지를 참조하십시오 . 그의 코드는 포함 된 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');

물론 도움이됩니다.


2
나는 이것이 해킹이 얼마나 추한지 이해하지만 확실히 나를 도왔다.
— lindhe

30

두 파일이 예 생성 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

26

main.js의 lib.js 파일에 있는 함수 ping () 및 add (30,20) 를 호출하고 싶다고 가정 해보십시오.

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
    }

1
이것은 작동하지만 스크립트를 포함 할 때 모듈 구문을 사용하지 않아야합니까?
— Kokodoko

25

Node.js의 vm 모듈은 현재 컨텍스트 (글로벌 객체 포함) 내에서 JavaScript 코드를 실행할 수있는 기능을 제공합니다. http://nodejs.org/docs/latest/api/vm.html#vm_vm_runinthiscontext_code_filename을 참조 하십시오.

현재 vm 모듈에는 runInThisContext가 새 컨텍스트에서 호출 될 때 올바르게 수행하지 못하도록하는 버그가 있습니다. 이것은 주 프로그램이 새로운 컨텍스트 내에서 코드를 실행 한 다음 해당 코드가 runInThisContext를 호출하는 경우에만 중요합니다. 참조 https://github.com/joyent/node/issues/898를

안타깝게도 Fernando가 제안한 with (global) 접근 방식은 "function foo () {}"와 같은 명명 된 함수에는 작동하지 않습니다.

간단히 말해 다음은 나를 위해 작동하는 include () 함수입니다.

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

다른 SO 답변에서 vm.runInThisContext를 발견했으며이를 사용하여 "vanilla"Javascript 코드 파일을 포함 시켰습니다. 그러나 노드 기능에 의존하는 코드 (예 : "var fs = require ( 'fs')")를 포함시키기 위해이를 사용하려고했지만 작동하지 않습니다. 그러나이 경우 몇 가지 답변에 언급 된 "평가"솔루션이 실제로 작동합니다.
— Dexygen

노드 기능에 의존하는 코드를 포함 할 필요가있을 때이를 조금 더 생각하면, 모듈을 작성해야 할 때가되었지만, eval 솔루션은 그 과정의 첫 단계 일 수 있습니다.
— Dexygen

2019 년 node.js에서 일한 사람
— Meesern

13

우도 지.

  • eval ()은 함수 내에서 사용될 수 없으며 전역 범위 내에서 호출되어야합니다. 그렇지 않으면 함수 나 변수에 액세스 할 수 없습니다 (즉, include () 유틸리티 함수 등을 만들 수 없음).

그는 옳지 만 함수에서 전역 범위에 영향을 미치는 방법이 있습니다. 그의 예를 개선 :

function include(file_) {
    with (global) {
        eval(fs.readFileSync(file_) + '');
    };
};

include('somefile_with_some_declarations.js');

// the declarations are now accessible here.

희망이 도움이됩니다.


12

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

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

Lib1.js를 node_modules 폴더에 저장하십시오 .


11

전역 변수에 함수를 넣을 수 있지만 도구 스크립트를 모듈로 바꾸는 것이 좋습니다. 실제로 그렇게 어렵지는 않습니다 exports. 퍼블릭 API를 객체에 연결하기 만하면 됩니다. 한 번 봐 가지고 이해 Node.js를 '수출 모듈 좀 더 세부 사항에 대한합니다.


1
예는 링크보다 낫습니다
— tno2007

11

내 의견으로는이 작업을 수행하는 또 다른 방법은, 당신이 호출 할 때 LIB 파일에 모든 것을 실행하는 것입니다 필요 () 함수를 사용하여 (기능 (여기에 / * 일 * /) {}) (); 이렇게하면 eval () 솔루션 과 마찬가지로이 모든 함수를 전역 범위로 만들 수 있습니다

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

받는 지불 하 atention 정의되지 않은 내 전화 object.funcFour ()는 당신이로드하는 경우, 그것은 같은 것입니다 평가 후면 () . 그것이 도움이되기를 바랍니다 :)


10

tools.js 에서 가져온 특정 함수 만 필요한 경우 버전 6.4 이후 node.js에서 지원되는 구조 지정 할당 을 사용할 수 있습니다 ( node.green 참조) .


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

tools.js

module.exports = {
    sum: function(a,b) {
        return a + b;
    },
    isEven: function(a) {
        return a % 2 == 0;
    }
};

main.js

const { isEven } = require('./tools.js');

console.log(isEven(10));

산출: true


또한 다음 (공통) 할당에서와 같이 해당 함수를 다른 객체의 속성으로 할당하지 않아도됩니다.

const tools = require('./tools.js');

어디로 전화해야합니까 tools.isEven(10)?


노트:

파일 이름 앞에 올바른 경로를 붙여야합니다. 두 파일이 모두 같은 폴더에 있더라도 접두사를 ./

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

파일을 나타내는 선행 '/', './'또는 '../'이 없으면 모듈은 핵심 모듈이거나 node_modules 폴더에서로드되어야합니다.


10

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 };

3

주어진 (전역이 아닌) 컨텍스트에서 파일을 포함하고 실행하십시오

fileToInclude.js

define({
    "data": "XYZ"
});

main.js

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

2

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

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;

2

당신이 파일을 가지고 abc.txt있고 더 많은 것처럼 ?

2 개의 파일을 작성 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());

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

파일 이름을 인수로 전달하고 있으며 모든 파일 readfile.js을 전달하는 대신 포함 하십시오.

감사


2

당신은 간단하게 할 수 있습니다 require('./filename').

예 :

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

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

  1. 하위 파일에서 PORT를들을 수 없으며, 부모 익스프레스 모듈 만 PORT 리스너를 갖습니다.
  2. 어린이가 부모 Express moudle이 아닌 'Router'를 사용하고 있습니다.

1

모듈을 작성하지 않고 코드를 포함하는 옵션을 찾고있었습니다. Node.js를 서비스에 대해 서로 다른 프로젝트에서 동일한 테스트를 독립 소스를 사용 - 그리고 jmparatte 의 대답은 나를 위해 그것을했다.

이점은 네임 스페이스를 오염시키지 않고 문제가 없으며 "use strict";잘 작동한다는 것입니다.

전체 샘플은 다음과 같습니다 .

로드 할 스크립트-/lib/foo.js

"use strict";

(function(){

    var Foo = function(e){
        this.foo = e;
    }

    Foo.prototype.x = 1;

    return Foo;

}())

SampleModule-index.js

"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'
    }

}

이것이 어떻게 든 도움이 되었기를 바랍니다.


1

node.js 및 express.js 프레임 워크를 사용할 때의 다른 방법

var f1 = function(){
   console.log("f1");
}
var f2 = function(){
   console.log("f2");
}

module.exports = {
   f1 : f1,
   f2 : f2
}

이것을 s라는 js 파일과 statics 폴더에 저장하십시오.

이제 기능을 사용하려면

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

1

HTML 템플릿을 위해 이것을 처리하는 다소 조잡한 방법을 생각해 냈습니다. PHP와 유사<?php include("navigation.html"); ?>

server.js

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));
});

page_name.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>

navigation.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>

0

여러 CPU 및 마이크로 서비스 아키텍처를 활용하려면 속도를 높이기 위해 ... 포크 프로세스보다 RPC를 사용하십시오.

복잡하게 들리지만 octopus 를 사용하면 간단합니다 .

예를 들면 다음과 같습니다.

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

공개-나는 문어의 저자이며 가벼운 라이브러리를 찾을 수 없기 때문에 비슷한 유스 케이스를 위해 만들어진 경우.


0

"도구"를 모듈로 바꾸는 데 전혀 어려움이 없습니다. 다른 모든 답변에도 불구하고 여전히 module.exports를 사용하는 것이 좋습니다.

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

이제이 내보내기를 전역 범위에 할당해야합니다 (app | index | server.js).

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

이제 함수를 다음과 같이 참조하고 호출 할 수 있습니다.

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

-3

사용하다:

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

app.js :

module.exports.<your function> = function () {
    <what should the function do>
}

1
전체 디렉토리를 거의 사용해서는 안됩니다. 다음과 같은 상대 경로 사용을 고려해야합니다../tools.js
— Matthew D Auld
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.