스크립트를 node.js REPL에 어떻게로드합니까?
foo.js
REPL에서 놀고 싶은 기능이 포함 된 스크립트 가 있습니다.
방법은 내 스크립트를 실행하고 내가 함께 할 수처럼 다음, 모든 선언 전역으로 REPL에 뛰어 노드 가지고 있는가 python -i foo.py
나 ghci foo.hs
?
설명하는 정확한 기능을 제공하기위한 내장 기능은 아직 없습니다. 그러나 require
이를 사용 하여 REPL 내에서 .load
명령 을 사용 하는 대안 은 다음과 같습니다.
.load foo.js
REPL에 입력 한 것처럼 파일을 한 줄씩로드합니다. 이와 달리 require
,로드 한 명령으로 REPL 기록을 오염시킵니다. 그러나와 같이 캐시되지 않기 때문에 반복 가능하다는 장점이 require
있습니다.
사용 사례에 따라 더 나은 방법이 있습니다.
편집 : 엄격 모드에서는 작동하지 않기 때문에 적용 가능성이 제한적이지만 3 년 후 스크립트에 없는 경우 REPL 기록을 오염시키지 않고 스크립트를로드 하는 데 사용할'use strict'
수 있다는 것을 알게되었습니다 .eval
var fs = require('fs');
eval(fs.readFileSync('foo.js').toString())
나는 항상이 명령을 사용합니다
node -i -e "$(< yourScript.js)"
패키지없이 파이썬에서와 똑같이 작동합니다.
노드 추가를 대화식 CLI로 전환하여이 문제를 처리하는 Vorpal.js를 만들었습니다 . REPL 확장을 지원하여 실행중인 앱의 컨텍스트 내에서 REPL로 연결됩니다.
var vorpal = require('vorpal')();
var repl = require('vorpal-repl');
vorpal
.delimiter('myapp>')
.use(repl)
.show()
.parse(process.argv);
그런 다음 앱을 실행할 수 있으며 REPL로 떨어집니다.
$ node myapp.js repl
myapp> repl:
스크립트를 반복적으로 다시로드하는 데 지쳐서 replpad를 만들었습니다 .
다음을 통해 간단히 설치하십시오. npm install -g replpad
그런 다음 다음을 실행하여 사용하십시오. replpad
현재 및 모든 하위 디렉토리의 모든 파일을보고 변경시 파일을 파이프에 파이프하려면 다음을 수행하십시오. replpad .
사이트의 비디오를 확인하여 작동 방식에 대한 더 나은 아이디어를 얻고 다음과 같은 다른 멋진 기능에 대해 알아보십시오.
dox()
모든 핵심 기능에 추가 된 기능을 통해 repl의 핵심 모듈 문서에 액세스fs.readdir.dox()
dox()
npm을 통해 설치된 모든 모듈에 추가 되는 기능을 통해 repl의 사용자 모듈 readme에 액세스합니다.marked.dox()
- 기능의 강조 표시된 소스 코드 , 기능이 정의 된 위치에 대한 정보 (파일, 줄 번호) 및 모든 기능에 추가 된 특성을 통해 가능한 경우 기능 설명 및 / 또는 jsdoc
src
express.logger.src
- scriptie-talkie 지원 (
.talk
명령참조) - 명령 및 키보드 단축키를 추가합니다
- vim 키 바인딩
- 키 맵 지원
- 일치하는 괄호 일치를 통해 토큰 플러그인
- 키보드 단축키 또는
.append
명령을 통해 repl에 입력 된 코드를 파일에 다시 추가
다른 방법은 해당 기능을 전역으로 정의하는 것입니다.
global.helloWorld = function() { console.log("Hello World"); }
그런 다음 REPL에 파일을 다음과 같이 사전로드하십시오.
node -r ./file.js
그런 다음 helloWorld
REPL에서 직접 기능에 액세스 할 수 있습니다.
대화식 노드 repl에 파일을로드하지 않는 이유는 무엇입니까?
node -h
-e, --eval script evaluate script
-i, --interactive always enter the REPL even if stdin
node -e 'var client = require("./build/main/index.js"); console.log("Use `client` in repl")' -i
그런 다음 package.json 스크립트에 추가 할 수 있습니다
"repl": "node -e 'var client = require(\"./build/main/index.js\"); console.log(\"Use `client` in repl\")' -i",
노드 v8.1.2를 사용하여 테스트
현재는 직접 할 수 mylib = require('./foo.js')
는 없지만 REPL에서 할 수 있습니다 . 전역으로 선언되지 않은 메소드가 내보내집니다.
replpad
is cool, but for a quick and easy way to load a file into node, import its variables and start a repl, you can add the following code to the end of your .js file
if (require.main === module){
(function() {
var _context = require('repl').start({prompt: '$> '}).context;
var scope = require('lexical-scope')(require('fs').readFileSync(__filename));
for (var name in scope.locals[''] )
_context[scope.locals[''][name]] = eval(scope.locals[''][name]);
for (name in scope.globals.exported)
_context[scope.globals.exported[name]] = eval(scope.globals.exported[name]);
})();
}
Now if your file is src.js
, running node src.js
will start node, load the file, start a REPL, and copy all the objects declared as var
at the top level as well as any exported globals. The if (require.main === module)
ensures that this code will not be executed if src.js
is included through a require
statement. I fact, you can add any code you want to be excuted when you are running src.js
standalone for debugging purposes inside the if
statement.
Another suggestion that I do not see here: try this little bit of code
#!/usr/bin/env node
'use strict';
const repl = require('repl');
const cli = repl.start({ replMode: repl.REPL_MODE_STRICT });
cli.context.foo = require('./foo'); // injects it into the repl
Then you can simply run this script and it will include foo
as a variable
Here's a bash function version of George's answer:
noderepl() {
FILE_CONTENTS="$(< $1 )"
node -i -e "$FILE_CONTENTS"
}
If you put this in your ~/.bash_profile
you can use it like an alias, i.e.:
noderepl foo.js
Old answer
type test.js|node -i
Will open the node REPL and type in all lines from test.js into REPL, but for some reason node will quit after file ends
Another problem is, that functions will not be hoisted.
Better answer
node -e require('repl').start({useGlobal:true}); -r ./test2.js
Then all globals declared without var within test2.js will be available in the REPL
not sure why var a in global scope will not be available
참고URL : https://stackoverflow.com/questions/8425102/how-do-i-load-my-script-into-the-node-js-repl
'Programming' 카테고리의 다른 글
가상 DOM이란 무엇입니까? (0) | 2020.07.15 |
---|---|
Windows 용 C 컴파일러? (0) | 2020.07.15 |
R에서 가장 다양한 색상을 생성하는 방법은 무엇입니까? (0) | 2020.07.15 |
각 그룹의 첫 번째 행을 선택하는 방법은 무엇입니까? (0) | 2020.07.15 |
안드로이드 : ScrollView vs NestedScrollView (0) | 2020.07.15 |