일부 코드를 실행 한 다음 대화 형 노드로 이동
node.js에서 대화 형 모드로 전환하기 전에 일부 코드 (파일 또는 문자열에서 실제로 중요하지 않음)를 실행하는 방법이 있습니까?
예를 들어 다음 __preamble__.js
을 포함 하는 스크립트 를 생성하는 경우 :
console.log("preamble executed! poor guy!");
사용자가 node __preamble__.js
입력하면 다음과 같은 출력이 나타납니다.
preamble executed! poor guy!
> [interactive mode]
정말 오래된 질문이지만 ...
나는 비슷한 것을 찾고 있었고, 나는 이것을 발견했습니다. REPL ( node
터미널에 입력) 을 열고 파일을로드 할 수 있습니다. 이렇게 : .load ./script.js
. Enter 키를 누르면 파일 내용이 실행됩니다. 이제 스크립트에서 생성 된 모든 것 (객체, 변수, 함수)을 사용할 수 있습니다.
예를 들면 :
// script.js
var y = {
name: 'obj',
status: true
};
var x = setInterval(function () {
console.log('As time goes by...');
}, 5000);
REPL에서 :
//REPL
.load ./script.js
이제 REPL을 입력하고 "리빙 코드"와 상호 작용합니다. 당신은 할 수 console.log(y)
또는 clearInterval(x)
;
약간 이상 할 것입니다. "시간이 지남에 따라 ..."가 5 초마다 (약) 계속 표시됩니다. 그러나 작동합니다!
repl
Node 소프트웨어에서 아주 쉽게 새로운 것을 시작할 수 있습니다 .
var repl = require("repl");
var r = repl.start("node> ");
r.context.pause = pauseHTTP;
r.context.resume = resumeHTTP;
REPL 내에서 함수 를 직접 호출 pause()
하거나 resume()
실행할 수 있습니다. REPL의 구성원 에게 노출하려는 모든 것을 지정하십시오 .pauseHTTP()
resumeHTTP()
context
이는 현재 버전의 NodeJS ( 5.9.1
)를 사용하여 수행 할 수 있습니다 .
$ node -i -e "console.log('A message')"
-e
플래그는 문자열을 평가하고 -i
플래그는 대화 형 모드를 시작합니다.
참조 된 pull 요청 에서 더 많은 것을 읽을 수 있습니다.
node -r
REPL이 시작될 때 모듈을 요구할 수 있습니다. NODE_PATH
모듈 검색 경로를 설정합니다. 따라서 명령 줄에서 다음과 같이 실행할 수 있습니다.
NODE_PATH=. node -r myscript.js
이렇게하면 스크립트가로드 된 REPL에 들어갑니다.
저는 최근에 Node와 CoffeeScript와 같은 관련 언어를위한 고급 대화 형 셸을 만드는 프로젝트를 시작했습니다. 기능 중 하나는로드 된 언어를 고려하는 시작시 인터프리터 컨텍스트에서 파일 또는 문자열을로드하는 것입니다.
http://danielgtaylor.github.com/nesh/
예 :
# Load a string (Javascript)
nesh -e 'var hello = function (name) { return "Hello, " + name; };'
# Load a string (CoffeeScript)
nesh -c -e 'hello = (name) -> "Hello, #{name}"'
# Load a file (Javascript)
nesh -e hello.js
# Load a file (CoffeeScript)
nesh -c -e hello.coffee
그런 다음 통역사에서 hello
기능에 액세스 할 수 있습니다 .
편집 : 무시하십시오. @ jaywalking101의 대답이 훨씬 낫습니다. 대신하십시오.
Bash 셸 (Linux, OS X, Cygwin) 내에서 실행중인 경우
cat __preamble__.js - | node -i
작동합니다. 이것은 또한 프리앰블 .js 의 각 줄을 평가할 때 많은 소음을 뿜어 내지 만 나중에 원하는 컨텍스트에서 대화 형 쉘에 도착합니다.
(The '-' to 'cat' just specifies "use standard input".)
Similar answer to @slacktracer, but if you are fine using global
in your script, you can simply require
it instead of (learning and) using .load
.
Example lib.js
:
global.x = 123;
Example node
session:
$ node
> require('./lib')
{}
> x
123
As a nice side-effect, you don't even have to do the var x = require('x'); 0
dance, as module.exports
remains an empty object and thus the require
result will not fill up your screen with the module's content.
Vorpal.js was built to do just this. It provides an API for building an interactive CLI in the context of your application.
It includes plugins, and one of these is Vorpal-REPL. This lets you type repl
and this will drop you into a REPL within the context of your application.
Example to implement:
var vorpal = require('vorpal')();
var repl = require('vorpal-repl');
vorpal.use(repl).show();
// Now you do your custom code...
// If you want to automatically jump
// into REPl mode, just do this:
vorpal.exec('repl');
That's all!
Disclaimer: I wrote Vorpal.
There isn't a way do this natively. You can either enter the node interactive shell node
or run a script you have node myScrpt.js
. @sarnold is right, in that if you want that for your app, you will need to make it yourself, and using the repl toolkit is helpful for that kind of thing
nit-tool lets you load a node module into the repl interactive and have access to inner module environment (join context) for development purposes
npm install nit-tool -g
참고URL : https://stackoverflow.com/questions/8549145/execute-some-code-and-then-go-into-interactive-node
'developer tip' 카테고리의 다른 글
JavaScript의 preg_match? (0) | 2020.11.07 |
---|---|
Redis db에서 모든 키 / 값 쌍 검색 / 나열 (0) | 2020.11.07 |
C # 4.0에서 작업을 절전 (또는 지연)하는 방법은 무엇입니까? (0) | 2020.11.07 |
Bash에서 읽기 전용 변수 설정 해제 (0) | 2020.11.07 |
Java의 enum에서 문자열 값 가져 오기 (0) | 2020.11.07 |