ASAR Archives
After creating an application distribution, the app's source code are usually bundled into an ASAR archive, which is a simple extensive archive format designed for Electron apps. By bundling the app we can mitigate issues around long path names on Windows, speed up require
and conceal your source code from cursory inspection.
The bundled app runs in a virtual file system and most APIs would just work normally, but for some cases you might want to work on ASAR archives explicitly due to a few caveats.
Using ASAR Archives
In Electron there are two sets of APIs: Node APIs provided by Node.js and Web APIs provided by Chromium. Both APIs support reading files from ASAR archives.
Node API
With special patches in Electron, Node APIs like fs.readFile
and require
treat ASAR archives as virtual directories, and the files in it as normal files in the filesystem.
Por ejemplo, supongamos que tenemos un archivo example.asar
en /path/to
:
$ asar list /path/to/example.asar
/app.js
/file.txt
/dir/module.js
/static/index.html
/static/main.css
/static/jquery.min.js
Read a file in the ASAR archive:
const fs = require('fs')
fs.readFileSync('/path/to/example.asar/file.txt')
Lista de todos las fichas debajo de la raíz del archivo:
const fs = require('fs')
fs.readdirSync('/path/to/example.asar')
Use un módulo del archivo:
require('./path/to/example.asar/dir/module.js')
You can also display a web page in an ASAR archive with BrowserWindow
:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.loadURL('file:///path/to/example.asar/static/index.html')
Web API
In a web page, files in an archive can be requested with the file:
protocol. Like the Node API, ASAR archives are treated as directories.
Por ejemplo, para obtener un fichero con $,obtenga
:
<script>
let $ = require('./jquery.min.js')
$.get('file:///path/to/example.asar/file.txt', (data) => {
console.log(data)
})
</script>
Treating an ASAR archive as a Normal File
For some cases like verifying the ASAR archive's checksum, we need to read the content of an ASAR archive as a file. Para este propósito usted puede usar el módulo incorporado original-fs
el cual provee APIs originales fs
sin el soporte de asar
:
const originalFs = require('original-fs')
originalFs.readFileSync('/path/to/example.asar')
También puede configurar process.noAsar
a Verdad
para inhabilitar el soporte de asar
en el módulo fs
:
const fs = require('fs')
process.noAsar = true
fs.readFileSync('/path/to/example.asar')
Limitaciones de la API de nodo
Even though we tried hard to make ASAR archives in the Node API work like directories as much as possible, there are still limitations due to the low-level nature of the Node API.
Archivos de solo lectura
The archives can not be modified so all Node APIs that can modify files will not work with ASAR archives.
Directorio de Trabajo No Puede Ser Configurado en Directorios en Archivos
Though ASAR archives are treated as directories, there are no actual directories in the filesystem, so you can never set the working directory to directories in ASAR archives. Al igual que con las opciones cwd
de algunas APIs también causarán errores.
Desempaque adicional en algunas APIs
Most fs
APIs can read a file or get a file's information from ASAR archives without unpacking, but for some APIs that rely on passing the real file path to underlying system calls, Electron will extract the needed file into a temporary file and pass the path of the temporary file to the APIs to make them work. Esto añadirá unos pequeños gastos adicionales para aquellas APIs.
Las APIs que requieren de un desempaquetado extra son:
child_process.execFile
child_process.execFileSync
fs.open
fs.openSync
process.dlopen
- Usado porrequire
en módulos nativos
Información estadística falsa de fs.stat
Los objetos Estadística
devuelto por fs.stat
y sus archivos amigos en archivos asar
son generados al azar, debido a que esos archivos no existen en el archivo de sistema. Así que no debe confiar en el objeto estadística
a excepción de que vaya a obtener el tamaño del archivo o verificar el tipo de este.
Executing Binaries Inside ASAR archive
There are Node APIs that can execute binaries like child_process.exec
, child_process.spawn
and child_process.execFile
, but only execFile
is supported to execute binaries inside ASAR archive.
Esto es debido a que exec
y spawn
acepta command
en vez de file
como entrada, y command
son ejecutados por debajo de la cáscara. No hay manera fiable de determinar si un comando usa un archivo en un archivo asar, y aún si lo hiciésemos, no podemos estar seguros si no podemos reemplazar el camino en comando sin efectos secundarios.
Adding Unpacked Files to ASAR archives
As stated above, some Node APIs will unpack the file to the filesystem when called. Aparte de los problemas de rendimiento, puede que varios escáneres de antivirus sean lanzados por este comportamiento.
As a workaround, you can leave various files unpacked using the --unpack
option. In the following example, shared libraries of native Node.js modules will not be packed:
$ asar pack app app.asar --unpack *.node
Después de ejecutar el comando, notará que una carpeta llamada app.asar.unpacked
fue creada en conjunto con el archivo app.asar
. Este contiene los archivos desempaquetados y debe ser enviado en conjunto con el archivo app.asar
.