87

Node.JS的竞争对手?QuickJS入门教程,使用os模块读写文件,并将JavaScript编绎成可执...

 5 years ago
source link: https://www.tuicool.com/articles/6bmI3uQ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

QuickJS 是一个完全由C语言编写的极小型JavaScript引擎,支持跨平台运行,并且有一些Java的特质,可将JS直接编绎成二进制文件。内置的系统模块还可以直接读写文件,动态加载脚本。目前还不支持net模块,不过已经有人在pull request中提交了merge请求。不久将可以直接使用系统Socket或发送http请求,构建web服务器。

由于非常精简,而且拥有JavaScript的全部功能,开发效率和运行效率都相当不错,可以预见,QuickJS将是Node.JS在嵌入设备,尤其是低端设备上较强的竞争对手。

QuickJS直接调用C模块

使用QuickJS前先需要进行源码编绎, 参考:  在嵌入式设备树莓派上编译QuickJS教程:一个C语言编写的极简JavaScript引擎 

QuickJS可直接调用C语言写的模块,如下面的示例:

/* example of JS module importing a C module */

import { fib } from "./fib.so";

console.log("Hello World");

console.log("fib(10)=", fib(10));

因为使用了import,调用时需要先启用模块加载 -m 参数:

root@VM-168-37-debian:~/quickjs-2019-07-09# ./qjs -m examples/hello_module.js

> Hello World

> fib(10)= 55

QuickJS使用系统os模块

在node.js中os提供系统的一些接口比如芯片构架操作系统信息等,文件操作则在fs模块中。而在quickjs中则在os模块中提供一些操作系统的底层接口,比如文件读写。

我们先创建一个测试文件,内容为 testing:

echo testing >> test.txt

新建一个 os.js 的测试文件,

nano os.js

粘贴入代码:

var fd      = os.open('./test.txt')

var buffer  = new ArrayBuffer(1024)

var len     = os.read(fd, buffer, 0, 1024)

console.log(len)

console.log(String.fromCharCode.apply(null, new Uint8Array(buffer)))

由于fd读取的是ArrayBuffer,我们使用了Uint8Array先转换成了字符串。用qs运行:

root@VM-168-37-debian:~/quickjs-2019-07-09# ./qjs os.js

8

testing

编绎成可执行文件

QuickJS使用qjsc来将javascript 文件编绎成二进制文件,但这里可能有一个BUG调用时目前还无法调用系统模块。没有外部依赖的JS则没有这个问题,由此可见QuickJS还有一定的改善空间。

root@VM-168-37-debian:~/quickjs-2019-07-09# ./qjsc -o os os.js
root@VM-168-37-debian:~/quickjs-2019-07-09# ./os
ReferenceError: os is not defined
    at <eval> (os.js:1)

这里的例子使用的是同步代码,由于JavaScript是单线程的,同步代码可能会阻塞当前进程,QuickJS提供了 setReadHandler/setWriteHandler 疑似可以传入回调函数进行异步处理。

os module 目前的接口方法:

open(filename, flags, mode = 0o666)

close(fd)

seek(fd, offset, whence)

read(fd, buffer, offset, length)

write(fd, buffer, offset, length)

isatty(fd)

ttyGetWinSize(fd)

ttySetRaw(fd)

remove(filename)

rename(oldname, newname)

setReadHandler(fd, func)

setWriteHandler(fd, func)

signal(signal, func)

setTimeout(delay, func)

clearTimer(handle)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK