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에서 사용하려면 어떻게 Import해야 합니까?
아니면... "도구"를 모듈로 변환하고, 그걸 요구해야 하나요?<< >는 어려울 것 같습니다만, 저는 tools.js 파일의 기본 Import를 합니다.
어떤 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";
("interface 모드"일 경우) "interface" 파일에 정의된 함수 및 변수는 가져오기를 수행하는 코드에서 액세스할 수 없기 때문입니다.strict 모드에서는 새로운 버전의 언어 표준에서 정의된 몇 가지 규칙이 적용됩니다.이는 여기서 설명하는 솔루션을 회피하는 또 다른 이유일 수 있습니다.
새로운 기능이나 모듈은 필요 없습니다.네임스페이스를 사용하지 않으려면 호출할 모듈을 실행하면 됩니다.
tools.module에 있습니다.
module.exports = function() {
this.sum = function(a,b) { return a+b };
this.multiply = function(a,b) { return a*b };
//etc
}
app.discloss에서
또는 myController.js와 같은 다른 .js:
대신
var tools = require('tools.js')
해서 '네임스페이스'라는 .tools.sum(1,2);
우리는 간단히 전화할 수 있다.
require('tools.js')();
그리고 나서.
sum(1,2);
제 경우 controlls.js가 포함된 파일이 있습니다.
module.exports = function() {
this.Categories = require('categories.js');
}
쓰면 요.Categories
class로서 뒤에 표시됩니다.require('ctrls.js')()
2개의 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
: 2개의 파일).app.js
★★★★★★★★★★★★★★★★★」tools.js
app.module
const tools= require("./tools.js")
var x = tools.add(4,2) ;
var y = tools.subtract(4,2);
console.log(x);
console.log(y);
tools.module
const add = function(x, y){
return x+y;
}
const subtract = function(x, y){
return x-y;
}
module.exports ={
add,subtract
}
산출량
6
2
다음은 알기 쉽고 간단한 설명입니다.
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 ()
{
};
저도 노드를 찾고 있었습니다.JS 'filength' 기능을 통해 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');
네, 그게 도움이 돼요.
JavaScript 일 2 2 2 。예2예 。import_functions.js
★★★★★★★★★★★★★★★★★」main.js
1) import_module.module
// Declaration --------------------------------------
module.exports =
{
add,
subtract
// ...
}
// Implementation ----------------------------------
function add(x, y)
{
return x + y;
}
function subtract(x, y)
{
return x - y;
}
// ...
2) 메인.메인.
// include ---------------------------------------
const sf= require("./import_functions.js")
// use -------------------------------------------
var x = sf.add(4,2);
console.log(x);
var y = sf.subtract(4,2);
console.log(y);
산출량
6
2
Node.js의 VM 모듈은 현재 컨텍스트(글로벌 개체 포함) 내에서 JavaScript 코드를 실행할 수 있는 기능을 제공합니다.http://nodejs.org/docs/latest/api/vm.html#vm_vm_runinthiscontext_code_filename 를 참조해 주세요.
현재 VM 모듈에는 실행 전 버그가 있습니다.이 컨텍스트는 새로운 컨텍스트에서 호출되었을 때 올바른 동작을 하지 않습니다.이것은 메인 프로그램이 새로운 컨텍스트 내에서 코드를 실행하고 그 코드 호출이 runIn을 실행하는 경우에만 문제가 됩니다.이 콘텍스트https://github.com/joyent/node/issues/898 를 참조해 주세요.
Fernando가 제안한 with(글로벌) 접근법은 "function foo() {}"와 같은 명명된 함수에서는 작동하지 않습니다.
즉, 다음과 같이 나에게 적합한 include() 함수가 있습니다.
function include(path) {
var code = fs.readFileSync(path, 'utf-8');
vm.runInThisContext(code, path);
}
예를 들어 함수 ping()을 호출하고 main.disc의 lib.disc 파일에 있는 추가(30,20)를 추가합니다.
main.discloss.main.discloss.
lib = require("./lib.js")
output = lib.ping();
console.log(output);
//Passing Parameters
console.log("Sum of A and B = " + lib.add(20,30))
lib.displaces
this.ping=function ()
{
return "Ping Success"
}
//Functions with parameters
this.add=function(a,b)
{
return a+b
}
Udo G.는 다음과 같이 말했다.
- eval()은 함수 내에서 사용할 수 없으며 글로벌 스코프 내에서 호출해야 합니다.그렇지 않으면 함수나 변수에 액세스할 수 없습니다(include() 유틸리티 함수 등을 만들 수 없습니다).
맞아요, 하지만 함수로 전 세계에 영향을 줄 수 있는 방법이 있어요예를 들면 다음과 같습니다.
function include(file_) {
with (global) {
eval(fs.readFileSync(file_) + '');
};
};
include('somefile_with_some_declarations.js');
// the declarations are now accessible here.
호프, 그게 도움이 되네
app.module
let { func_name } = require('path_to_tools.js');
func_name(); //function calling
tools.module
let func_name = function() {
...
//function body
...
};
module.exports = { func_name };
그것은 다음과 같이 나에게 작용했다.
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 폴더에 저장해야 합니다.
또 다른 방법은 (function(/* things here */){})(를 사용하여 require() 함수를 호출할 때 lib 파일 내의 모든 기능을 실행하는 것입니다.이렇게 하면 eval() 솔루션과 마찬가지로 모든 함수가 글로벌 스코프가 됩니다.
src/lib.syslog
(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.discloss.main.discloss.
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
내 오브젝트를 호출할 때 정의되지 않은 자에게 지불하십시오.funcFour()는 eval()을 사용하여 로드해도 동일합니다.도움이 되었으면 좋겠다:)
함수를 글로벌 변수에 넣을 수 있지만 도구 스크립트를 모듈로 변환하는 것이 좋습니다.그다지 어렵지 않습니다.퍼블릭 API를exports
물건.자세한 내용은 Node.js 내보내기 모듈을 참조하십시오.
tools.js에서 Import된 특정 함수만 필요한 경우 버전 6.4 이후 node.js에서 지원되는 파괴 할당을 사용할 수 있습니다(node.green 참조).
예: (두 파일이 같은 폴더에 있음)
tools.module
module.exports = {
sum: function(a,b) {
return a + b;
},
isEven: function(a) {
return a % 2 == 0;
}
};
main.discloss.main.discloss.
const { isEven } = require('./tools.js');
console.log(isEven(10));
출력: true
이렇게 하면 다음(공통) 할당에서와 같이 이러한 함수를 다른 개체의 속성으로 할당하지 않아도 됩니다.
const tools = require('./tools.js');
전화할 곳tools.isEven(10)
.
주의:
파일 이름 앞에 올바른 경로를 붙이는 것을 잊지 마십시오. 두 파일이 같은 폴더에 있더라도 접두사는 다음과 같습니다../
Node.js 문서에서:
선행 '/', '/', 또는 '..'가 없는 경우/'는 파일을 나타내려면 모듈이 핵심 모듈이거나 node_discounts 폴더에서 로드되어 있어야 합니다.
지정된 (글로벌하지 않은) 컨텍스트에서 파일 포함 및 실행
fileToInclude 입니다.js
define({
"data": "XYZ"
});
main.discloss.main.discloss.
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;
심플하게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;
주의해 주십시오.
- 자식 파일에서 PORT를 수신할 수 없습니다. 부모 express 모듈에만 PORT 리스너가 있습니다.
- 자녀가 부모 Express Moudle이 아닌 '라우터'를 사용하고 있습니다.
노드는 commonjs 모듈 및 최근에는 esm 모듈을 기반으로 작동합니다.기본적으로 분리된 .js 파일에 모듈을 만들고 Import/exports(module.exports 및 require)를 사용해야 합니다.
브라우저의 Javascript는 범위에 따라 다르게 작동합니다.글로벌 스코프가 있으며 클로저(다른 함수 내부의 함수)를 통해 개인 스코프를 사용할 수 있습니다.
따라서 노드에서는 다른 모듈에서 사용할 함수 및 개체를 내보냅니다.
IMO의 가장 깨끗한 방법은 다음과 같습니다.In tools . js :
function A(){
.
.
.
}
function B(){
.
.
.
}
module.exports = {
A,
B
}
그런 다음 app.js에서 다음과 같이 tools.js만 요구하면 됩니다.const tools = require("tools");
모듈을 작성하지 않고 코드를 포함하는 옵션도 찾고 있었습니다, responseNode.js 서비스에 대해 다른 프로젝트의 동일한 테스트된 독립 실행형 소스를 사용합니다.jmparatets의 답변이 도움이 되었습니다.
장점은, 당신이 네임스페이스를 오염시키지 않는다는 것입니다. 저는 이 문제를 해결하는데 문제가 없습니다."use strict";
잘 작동해요.
다음은 전체 샘플입니다.
로드할 스크립트 - /lib/foo.js
"use strict";
(function(){
var Foo = function(e){
this.foo = e;
}
Foo.prototype.x = 1;
return Foo;
}())
Sample Module - 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'
}
}
이게 도움이 됐으면 좋겠네요.
을 있는 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.disc --file=disc.discs.txt
모든 을 인수로 합니다.readfile.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 파일과 폴더 statics에 저장합니다.
이 기능을 사용하려면
var s = require('../statics/s');
s.f1();
s.f2();
"도구"를 모듈로 바꾸려면 저는 전혀 어렵지 않습니다.다른 모든 답변에도 불구하고 module.exports 사용을 권장합니다.
//util.js
module.exports = {
myFunction: function () {
// your logic in here
let message = "I am message from myFunction";
return message;
}
}
이제 이 내보내기를 글로벌 스코프에 할당해야 합니다(앱 | index | server.js )
var util = require('./util');
이제 다음과 같이 함수를 참조 및 호출할 수 있습니다.
//util.myFunction();
console.log(util.myFunction()); // prints in console :I am message from myFunction
을 ./test.js
UNIX 환경에서는 다음과 같은 것을 사용할 수 있습니다.
>> node -e "eval(''+require('fs').readFileSync('./test.js'))" -i
...
용도:
var mymodule = require("./tools.js")
app.filename:
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
'programing' 카테고리의 다른 글
문자열의 마지막 두 문자를 선택하는 방법 (0) | 2022.09.23 |
---|---|
Android 앱이 온라인 mysql 데이터베이스에 직접 연결할 수 있습니까? (0) | 2022.09.23 |
Laravel 마이그레이션 테이블이 이미 있지만 이전 테이블이 아닌 새 테이블을 추가하려고 합니다. (0) | 2022.09.23 |
익명 함수를 매개 변수로 사용하여 외부 변수 액세스 (0) | 2022.09.23 |
팬더: 지정된 열에 대한 데이터 프레임 행의 합계 (0) | 2022.09.23 |