ProgramingTip

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

bestdevel 2020. 9. 28. 09:36
반응형

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


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 파일의 기본 가져 오기를 수행합니다.


모든 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

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

var fs = require('fs');

// file is included here:
eval(fs.readFileSync('tools.js')+'');
  • 빈 공유 연결 +''은 파일 내용을 객체가 아닌 클래스로 가져 오는 데 필요합니다 ( .toString()원하는 경우 사용할 수도 있음 ).
  • eval ()은 함수 내에서 사용할 수 전역 범위 내에서 호출 해야합니다. 명명되지 않은 함수 나 변수에 액세스 할 수 없습니다 (예 : include()유틸리티 함수 등을 만들 수 없습니다 ).

대부분의 경우 나쁜 습관은 대신 모듈을 작성 해야 합니다 . 스페이스의 오염이 실제 상황이 드물게 있습니다.

업데이트 2015-08-06

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


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

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')()


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

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

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

또한 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');

물론입니다.


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
    }

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

Udo G. 메시지 :

  • eval ()은 함수 내에서 사용할 수있는 전역 범위 내에서 호출합니다. (즉, () 유틸리티 함수 등을 만들 수 없습니다).

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

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

include('somefile_with_some_declarations.js');

// the declarations are now accessible here.

희망, 도움이됩니다.


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


이 작업을 수행하는 또 다른 방법은 (function (/ * things here * /) {}) ();을 사용하여 require () 함수를 호출 할 때 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

my object.funcFour () 를 호출 할 때 undefined에 주의하십시오 . eval ()로 로드해도 동일합니다 . 도움이되기를 바랍니다 :)


다음과 같이 저와 함께 일했습니다 ....

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 폴더 에 두는 것을 잊지 마세요 .


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 폴더에서로드되어야합니다.


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

이 완전한 샘플 코드를 사용합니다. 다음 예제와 같이 지정된 함수를 포함하는 곳에 메소드 require사용하여 해당 파일 app.js을 포함 main.js해야합니다.

app.js

const mainFile= require("./main.js")


var x = mainFile.add(2,4) ;
console.log(x);

var y =  mainFile.multiply(2,5); 
console.log(y);

main.js

const add = function(x, y){
    return x+y;
}
const multiply = function(x,y){
    return x*y;
}

module.exports ={
    add:add,
    multiply:multiply
}

많이

6
10

파일을 포함하고 주어진 (비 글로벌) SQL에서 실행

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

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

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;

파일 abc.txt이있는 것처럼 ?

2 개의 파일 생성 : fileread.jsfetchingfile.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대신 모든 파일을 포함 합니다.

감사합니다


당신은 단지 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 모듈이 아닌 '라우터'를 사용하고 있습니다.

모듈을 작성하지 않고 코드를 포함하는 옵션을 찾고 있습니다. 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'
    }

}

이것이 어떻게 든 도움이 되었습니까?


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

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

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

관리자는 js 파일과 statics 폴더에 저장하십시오.

이제 기능을 사용하는 비용

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

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>

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

공개-문어의 저자이며, 가벼운 라이브러리를 구축하기 때문에 구축을 사용했습니다.


"도구"를 모듈로 바꾸는 것은 전혀 어렵지 않습니다. 다른 모든 답변에도 불구하고 여전히 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 

사용하다 :

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

app.js :

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

참고 URL : https://stackoverflow.com/questions/5797852/in-node-js-how-do-i-include-functions-from-my-other-files

반응형