JavaScript shell 介绍

翻译不完整。 请帮助我们翻译这篇文章!

JavaScript shell 是一个命令行程序,它被包含在SpiderMonkey源代码中。它在JavaScript中类似于Python的交互式提示符(即Python的命令行工具),Lisp中的读取执行打印循环工具,或者想Ruby中的irb。这篇文章解释如何使用shell去测试JavaScript代码,并且执行JavaScript程序。

得到 SpiderMonkey JavaScript shell, 参考SpiderMonkey Build Documentation or 根据你的平台下载二进制文件 Nightly Builds.

对于其他的 JavaScript shells, 参考 JavaScript shells.

Note: 由SpiderMonkey 44 (Firefox 44 / Thunderbird 44 / SeaMonkey 2.41)起始, 一个标准的, Web可编译的 JavaScript 版本使用默认版本 (不再是JS1.7+ ).  version() 函数用于测试特性。

执行JavaScript shell

shell提供两种操作模式。你既可以交互式操作shell, 在此模式你可以输入JavaScript 代码并执行。便于实验和测试新特性。你也可以在命令行参数指定一个JavaScript 代码文件,此文件会自动运行。

在构建并使用make install安装shell之后,你可以执行以下命令打开交互式终端:

js

[ 如果在使用预编译的二进制文件时出现" symbol lookup error: ./js: undefined symbol: PR_SetCurrentThreadName"可以尝试   /run-mozilla.sh ./js ]

如果运行 foo.js file中的JavaScript代码,你可以使用以下命令:

js foo.js

j运行 foo.js 然后进入交互模式:

js -f foo.js -i

说明

Note: 因为JavaScript shell 用来给 JavaScript 引擎做测试环境, 可用的选项和内置函数可能改变。

命令行选项

有许多命令行选项可以控制shell,以下为总结。使用-h选项显示帮助

-c, --compileonly
仅编译不执行代码,这是一种方便的检查语法错误的方式
-e script
运行指定脚本,script是将要执行的代码字符串.
-f filename
执行指定的代码文件.
-i
交互模式
--no-ion
    优化 JIT compiler无效.
--no-baseline
使底线 JIT compiler无效.
-P
如果文件的第一行是 "/usr/bin/env js -P",文件内容将通过 JavaScript 引擎解释.
这使你能够在*NIX机上使JavaScript可执行
-s
启用严格的警告模式.
-w, --warnings
启用警告消息.
-W, --nowarnings
禁用警告消息.

环境选项

有一些环境变量能够被设置去修改 js shell行为.

JS_STDOUT=file
将标准输出重定向到文件.
JS_STDERR=file
将标准输入重定向到文件.

内置方法

To make the JavaScript shell more useful, there are a number of built-in functions provided that you can use either from JavaScript programs or in interactive mode.

Note: 这个列表是不完整的且与 Shell global objects交叉. See js/src/shell/js.cpp (around shell_functions) for more.

build()

JavaScript shell构建的日期和时间.

Note: clear() 不带参数时将清除包括所有内置方法在内的所有东西

clone(function, [scope])

克隆指定函数对象. 如果未指定具体域, 新对象的父本和原始对象的相同. 否则,新对象被放置于指定域.

countHeap([start[, kind]])

Added in SpiderMonkey 1.8  计数堆中的动态GC, 或从start可达的. kind'all' (默认值)时计数所有,是 'object', 'double', 'string', 'function', 'qname', 'namespace', 'xml' 之一时,仅计数对应类别

dumpHeap([fileName[, start[, toFind[, maxDepth[, toIgnore]]]]])

Added in SpiderMonkey 1.8 转储所有现存对象的图(或其子图) 到文件. 详情参见本函数的C/C++版本: JS_DumpHeap.

evalcx(string[, object])

用字符串评估JavaScript代码. 如果对象被指定,代码将在该对象中执行,将其视为sandbox.

string为空且对象未指定时, evalcx() 返回一个新对象 with eager standard classes.

string为"lazy" 且对象未指定时, evalcx() 返回一个新对象 with lazy standard classes.

Note: evalcx() 仅对进行JavaScript引擎极低层工作的开发者有用,用于在shell中测试 类似evalInSandbox环境

gc()

运行垃圾收集器释放内存

gcparam(name[, value])

Added in SpiderMonkey 1.8 读取或配置垃圾收集器参数.

名称必须是参数key之一 (例如 'maxBytes', 'maxMallocBytes''gcNumber').

如果value未指定,gcparam()返回与GC参数名name相关联的当前值

如果value被指定,其必须可转换为uint32,gcparam()将GC参数名设置为value。

For more information, see the C/C++ functions  JS_SetGCParameter and JS_SetGCParameter.

gczeal(level)

Added in SpiderMonkey 1.8 DEBUG only. 设置GC zeal级别, 这是一个调试特性。0 是正常的周期性垃圾收集,1是频繁的GC, 2是及其频繁的GC. 除了0以外的都将使JavaScript运行极其缓慢但是可能有助于发现GC相关的 bug. For more information, see the C/C++ version of this function, JS_SetGCZeal.

getpda(object)

返回指定对象的属性描述

getslx(object)

返回脚本行范围,这是包含指定对象的代码行数

help([command ...])

Displays brief help information about the specified commands, or about all available functions if none are specified.

intern(string)

将指定的字符串 内化到atom表中。每个字符串都有一个唯一的标识符,称为atom。这个系统使得对字符串进行比较变得更加容易。

Note: This function is intended only for use when testing the JavaScript engine.

line2pc([function, ] line)

返回对应于指定行的代码行的程序计数器值。如果指定了函数,那么行就是指定函数的偏移量.

load(filename1 [filename])

加载带有指定名称的JavaScript文件.

Note: For loading non-JavaScript files, use read().

options([option ...])

让你设置或获取选项。如果您在命令行上指定选项,那么调用options的结果将指示您所请求的选项。您还可以传递新的选项来设置.

The available options are:

Option Name Description
strict 严格模式 is enabled.
werror Warnings should be treated as errors.
atline When atline is enabled, 表单的注释 //@line num set the number of the following line to num.

pc2line(function, [pc])

返回对应于指定函数的第一行的JavaScript代码的行号. If you specify a program counter offset into the function, the line number of the line of code containing that offset is returned.

print([expression ...])

Evaluates the expression(s) and displays the result(s) on stdout, 分隔 by spaces (" ") and 终止 by a newline ("\n").

putstr(expression)

Evaluates the expression and displays the result on stdout.

quit([status])

Exits the shell. 如果省略,状态默认为0。

read(filename[, type])

Reads and returns the contents of file. If type is "binary" returns an Uint8Array, otherwise returns an UTF-8 decoded string.

readline()

Reads a single line of input from stdin, returning it to the caller. You can use this to create interactive shell programs in JavaScript.

Reflect.parse()

See Parser API.

Note: This function is intended only for use when testing the JavaScript engine.

seal(object[, deep])

密封指定的对象, or an object graph if deep is true. 通过封住对象或对象图,可以禁用这些对象的修改.

sleep(dt)

Added in SpiderMonkey 1.8 Only in JS_THREADSAFE builds. Sleep for dt seconds. Fractions of a second are supported. Returns true on success, false if the sleep was interrupted.

stackQuota([number])

Added in SpiderMonkey 1.8 获取或设置脚本堆栈配额.

throwError()

Throws an error from the JS_ReportError() function.

Note: This function is intended only for use when testing the JavaScript engine.

trap([function, [pc,]] expression)

在JavaScript代码的特定点设置trap. 当由pc在函数函数中指定的偏移量即将被执行时,表达式将被求值。

这是一种强大的调试机制,与line2pc()一起使用. 例如, 如果你想在函数的第6行中显示一条消息, doSomething() 被执行, you can enter the following:

trap(doSomething, line2pc(doSomething, 6), "print('line 6!\n')");
Note: 当设置陷阱时,程序中的相应字节码将被trap字节码替换,直到您使用untrap() 来移除陷阱。

untrap(function [, pc])

Removes a trap from the specified function at the offset pc. If pc isn't specified, the trap is removed from the function's entry point.

This function has no effect if there is no trap at the specified location.

version([number])

The version() function lets you get or set the JavaScript version number. This may be useful for gaining access to syntax only available in certain versions of JavaScript (for example, see Using JavaScript 1.7).

调试方法

These built-in functions are only available in DEBUG builds.

dis([function])

为整个程序或指定的函数分解JavaScript字节码

For example, if you enter the JavaScript function below:

function test() {
  var i = 3;
  print(i+2);
}

Then run the command dis(test);, you get this output:

main:
00000:  uint16 3
00003:  setvar 0
00006:  pop
00007:  name "print"
00010:  pushobj
00011:  getvar 0
00014:  uint16 2
00017:  add
00018:  call 1
00021:  pop
00022:  stop

Source notes:
  0:     0 [   0] newline 
  1:     3 [   3] decl     offset 0
  2:     7 [   4] newline 
  3:    18 [  11] xdelta  
  4:    18 [   0] pcbase   offset 11

dissrc([function])

Disassembles the JavaScript bytecode for the entire program, or for the specified function, showing the source lines. This function only works with programs loaded from files, either using the -f flag on launching the shell, or by using the load() function.

If your program includes a function, doStuff(), like this:

function doStuff(input) {
	print("Enter a number: ");
	var n1 = readline();
	print("Enter another one: ");
	var n2 = readline();
	
	print("You entered " + n1 + " and " + n2 + "\n");
}

Calling dissrc(doStuff) function would give this output:

;-------------------------  10:         print("Enter a number: ");
00000:  10  name "print"
00003:  10  pushobj
00004:  10  string "Enter a number: "
00007:  10  call 1
00010:  10  pop
;-------------------------  11:         var n1 = readline();
00011:  11  name "readline"
00014:  11  pushobj
00015:  11  call 0
00018:  11  setvar 0
00021:  11  pop
;-------------------------  12:         print("Enter another one: ");
00022:  12  name "print"
00025:  12  pushobj
00026:  12  string "Enter another one: "
00029:  12  call 1
00032:  12  pop
;-------------------------  13:         var n2 = readline();
00033:  13  name "readline"
00036:  13  pushobj
00037:  13  call 0
00040:  13  setvar 1
00043:  13  pop
;-------------------------  14: 
;-------------------------  15:         print("You entered " + n1 + " and " + n2 + "\n");
00044:  15  name "print"
00047:  15  pushobj
00048:  15  string "You entered "
00051:  15  getvar 0
00054:  15  add
00055:  15  string " and "
00058:  15  add
00059:  15  getvar 1
00062:  15  add
00063:  15  string "\\n"
00066:  15  add
00067:  15  call 1
00070:  15  pop
00071:  15  stop

dumpheap(([fileName[, start[, toFind[, maxDepth[, toIgnore]]]]])

Dump GC information. This is a thin wrapper for JS_DumpHeap.

gczeal(zeal)

Enable extra-frequent GC, to help find GC hazards. zeal is an integer. The meaning is the same as for the parameter to JS_SetGCZeal.

notes([function])

Shows the source notes for the specified function. Source notes contain information that map the bytecode to the source code, which is used when decompiling the code, such as when using the dissrc() function.