emacs-orgmode
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [O] Hope ob-js can support :session feature


From: Martin Alsinet
Subject: Re: [O] Hope ob-js can support :session feature
Date: Fri, 22 Dec 2017 18:32:07 +0000

Hello stardiviner,

On Fri, Dec 22, 2017 at 6:57 AM stardiviner <address@hidden> wrote:

I wish to do _javascript_ Literate Programming in Org-mode.

So the :session header argument is very necessary.


I do Literate Programming in _javascript_ with Org-mode, and I have found a workaround using a combination of tangled files and require.

I separate the logic in source code blocks which then I tangle into js files and I require those js files in other source blocks.

Example: 

#+BEGIN_SRC js :tangle src/parser.js
const fs = require('fs');
const parse = require('csv-parse')

function columns(line){
    return line.map(s => s.toLowerCase());
}
parse_csv = function(filename, fn, limit){
    fs.readFile(filename, "utf8", function (err, fileData) {
        var opts = {columns: columns, trim: true};
        if (limit) {
            opts.to = limit;
        }
        parse(fileData, opts, (err, rows) => fn(rows));
    });
}
module.exports = parse_csv;
#+END_SRC

So, I tangle that source block into a js file, and then I can use it from other blocks, without needing sessions at all:

#+BEGIN_SRC
const parser = require("/app/src/parser.js");
const inputFile = './data/records.csv';
parse_csv(inputFile, console.log);
#+END_SRC

The only drawback is that you have to use absolute paths requiring the js files, but since I am using docker containers to run node, I always mount the current directory as a volume in /app inside the container, so that works out fine.
I also think that this way forces me to separate the code in modular blocks, which is already a good practice in itself.
With sessions you have to make sure to execute the blocks in the correct order to build the "state" that your current block needs. 
This way source blocks function as standalone units that can be run at any time, I just run org-babel-tangle and then hit C-c inside the js block.

I hope that helps you.


Martin

reply via email to

[Prev in Thread] Current Thread [Next in Thread]