Execute 'fc -ln -1' (bash history) in node.js spawn - javascript

I've been searching for an answer and I couldn't find one (perhaps I'm not searching well). The issue is as follows:
var spawn = require('child_process').spawn;
var proc = spawn('fc', ['-ln', '-1']);
proc.stdout.on('data', function (data) {
console.log(data.toString('utf-8'));
});
proc.stderr.on('data', function (data) {
console.log('Error: ' + data.toString('utf-8'));
});
proc.on('close', function (code) {
console.log(code);
});
When I run this node script, it outputs '0' and nothing else. Apparently spawn works, but it doesn't output the history. I've tried with many combinations, but fc command simply doesn't output anything. I've also tried with exec and execSync. Neither output anything.
Is there a way to get the bash history from node.js? What am I missing?
Update:
According to this, bash history commands can't be output inside a shell script. That might mean that from spawned child processes, it still holds true. I gave up trying to get the last used command, since Etan made me realize that there's no easy way to tell the "last used command" in interactive multi sessions. I am now trying to read the $HISTFILE shell var (history file location) from inside Node with no luck yet.
Any ideas?
Update 2:
I just hardcoded most used shells history routes (bash, zsh, fish) and read the file directly. However I'll leave this open since I learned a lot about shell scripting, and hopefully this will help someone else. The key vars to use in Node (at least in Mac) are process.env.SHELL and process.env.HOME, to build the file route.

Related

Node.js user input wont work, readline-sync and error code 134

I'm coding a project in node.js on vs code and need an user input for various functions. I tried many libraries such as readline-sync or prompt-sync-plus but none of them work for me. While using readline-sync I always get the error: Process exited with code 134 and can't figure out what I'm doing wrong:
import readlineSync from 'readline-sync';
const name = readlineSync.question("Whats the name of the movie?")
console.log(name)
"Error: Process exited with code 134"
Can someone help me?
I tried to update node.js and readline-sync but it wont help. I also tried the readlineSync.question function in a different file so that I can exclude my code from the equation but its still not working
The readline-sync library provides a synchronous interface to read data from a readable stream. When using this library in a Node.js project, you may encounter a Process exited with code 134 error, which usually indicates a problem with the process running in the background.
Try to run this code separately and see if it works.
const readlineSync = require('readline-sync');
const name = readlineSync.question('What is your name? ');
console.log(`Hello, ${name}!`);
try using the built-in process.argv
https://nodejs.org/docs/latest/api/process.html#processargv
--> const userInput = process.argv.slice(number);
the number should be the number of arguments to be sliced off
--> node run myApplication "input1" --> number = 2

cannot find a module from a different database in marklogic

OK i have a MarkLogic 9.0.2 database in which I have two applications deployed. Lets say A and B. Now I want to run some code inside B from A, we can do this with the xdmp.eval() but the code I want to run needs to find a module deployed in the modules database of B.
I cannot seem to get this working.
Code run inside database B works :
declareUpdate();
var prj = require('/root/lib/project-lib.xqy');
prj.createProject('giraffe', 'A project about giraffes');
finds and runs the createProject function in the module library...
Now from database A I try to run this by an xdmp.eval() like so:
declareUpdate();
var options = { "isolation" : "different-transaction",
"database" : xdmp.database("data-hub-FINAL"),
"modules" : xdmp.database("data-hub-MODULES")
}
xdmp.eval("declareUpdate();var prj = require('/root/lib/project-lib.xqy');prj.createProject('fromcluey giraffe', 'A project about giraffes from cluey');"
, options);
But gives me:
[javascript] XDMP-MODNOTFOUND: declareUpdate();var prj = require('/root/lib/project-lib.xqy');prj.createProject('fromcluey giraffe', 'A project about giraffes from cluey'); -- Module /root/lib/project-lib.xqy not found
Can someone tell me how I am supposed to find the project-lib.xqy module from inside A?
Document permissions was the first thing I was thinking of, which also applies to modules, schemas, triggers etc, not just to documents. Privileges second. Modules root can definitely be important as well.
However, there is a simple typo in the above xdmp.eval that is the biggest culprit here: the function takes 3 arguments, not 2. And options is the 3rd, not the second.
It should be: xdmp:eval("...", null, options).
HTH!

Durandal requiring viewmodel from shell

In my app, I have a global player. In the shell module, I require the viewmodel of the player because I want to know if the player is playing, and if so, I add a class to container of the app (which is in the shell).
The problem is that I also need to require the shell from the player VM, because there are some functions that I use across the app that are in the shell.
But when requiring the player module from the shell, requiring the shell from the player returns undefined. If I don't require the player, the shell is passed normally.
shell.js
define(['viewmodels/player'], function(player) {
return {
player: player
}
})
player.js
define(['viewmodels/shell'], function(shell) {
console.log('shell:', shell) // undefined
})
I don't have any ideia of what's going on.
Hm!
I think I we had this problem once. They way it happens is require checks what's need by shell. Then it sees player module and goes to fix that, and inside that you requuire shell. Circular reference. We did solve it though.
We did like this, I'm writing psuedo code but you should be able to try this.
There are lots of ways, this is one easy way to do it. Open your player and do like this.
var shell = require('shell'); //using this style to work around circular reference
I will try to help with some implementation alternatives!
1º! player could be a service (singleton), and be required in bouth viewmodes,
// app/services/player.js
require([], function(){/*Player*/});
// shell
require(['services/player'], function(player){/* SHEll */});
// ohter view
require(['services/player'], function(player){/* other view*/});
2º You can use pub/sub pattern! Durandal has a support for that!
// Alert that play has been clicked
app.trigger('player:play');
// subscribe play
app.on('player:play', doSomething);
// deactivate subscription
app.off('player:play', doSomething);
Check documentation!
Booth work just fine and with low coupling...

Moving created files with JXA

I'm new to JXA scripting, but I'm attempting to troubleshoot some older scripts currently in place here at work. They loop through an InDesign document and create several PDFs based on it. Previously, they would be stored in a folder called "~/PDFExports". However, this doesn't work with 10.10.
If I change the code to just place the PDFs in "~/", it works fine. From there, I'd like to move the files to "~/PDFExports", but I can't seem to find an answer on how to do that. I've seen things about making calls to ObjC, or to call Application('Finder'), but neither work - they both return undefined.
Am I just missing something basic here, or is it really this hard to simply move a file with JXA?
EDIT: Some syntax for how I'm creating the folder in question and how I'm attempting to work with Finder.
//This is called in the Main function of the script, on first run.
var exportFolder = new Folder(exportPath);
if(!exportFolder.exists) {
exportFolder.create();
}
//This is called right after the PDF is created. file is a reference to the
actual PDF file, and destination is a file path string.
function MoveFile(file,destination){
var Finder = Application("Finder");
Application('Finder').move(sourceFile, { to: destinationFolder });
alert("File moved");
}
Adobe apps have long included their own embedded JS interpreter, JS API, and .jsx filename extension. It has nothing to do with JXA, and is not compatible with it.
InDesign's JSX documentation:
http://www.adobe.com/devnet/indesign/documentation.html#idscripting
(BTW, I'd also strongly advise against using JXA for Adobe app automation as it has a lot of missing/broken features and application compatibility problems, and really isn't fit for production work.)
Here's the link to Adobe's InDesign Scripting forum, which is the best place to get help with JSX:
https://forums.adobe.com/community/indesign/indesign_scripting
You could use Cocoa to create the folder
var exportFolder = $.NSHomeDirectory().stringByAppendingPathComponent("PDFExports")
var fileManager = $.NSFileManager.defaultManager
var folderExists = fileManager.fileExistsAtPath(exportFolder)
if (!folderExists) {
fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(exportFolder, false, $(), $())
}
and to move a file
var success = fileManager.moveItemAtPathToPathError(sourceFile, destinationLocation, $());
if (success) alert("File moved");
Consider that destinationLocation must be the full path including the file name
and both sourceFile and destinationLocation must be NSString objects like exportFolder
Could it be that the folder is missing ? Could be your reference to the folder object not valid ? Any syntax to show ?
I will share some of what I learned about JXA move and duplicate methods. I am not a professional programmer just an attorney that is passionate about automation. My comments come from much trial and error, reading whatever I could find online, and A LOT of struggle. The move method does not work well with Finder. Use the System Events move method instead. The duplicate method in Finder works just fine. The duplicate method does not work well in system events. This is a modified snippet from a script I wrote showing move() using System Events.
(() => {
const strPathTargetFile = '/Users/bretfarve/Documents/MyFolderA/myFile.txt';
const strPathFolder = '/Users/bretfarve/Documents/MyFolderB/';
/* System Events Objects */
const SysEvents = Application('System Events');
const objPathFolder = SysEvents.aliases[strPathFolder];
SysEvents.move(SysEvents.aliases.byName(strPathTargetFile), {to: objPathFolder});
})();

Forking in NodeJS

I'm a little bit confused as to how to create daemons in NodeJS
I've created daemons in C before that call fork() that continue execution from where the call was made in a child process allowing the parent to terminate. I can't readily achieve the same affect using process.fork() and process.kill().
The following code doesn't do what I expected and breaks:
var current_pid, cp = require('child_process');
current_pid = process.pid;
cp.fork('');
process.kill(current_pid);
The following error is emitted and I can't work out why or what's happening:
node.js:202
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: read EBADF
at errnoException (net.js:589:11)
at Pipe.onread (net.js:335:20)
The problem call appears to be process.kill(). Removing this, both processes continue to happily run.
I'm aware of daemon.node, but this was created at the time when child_process.fork() didn't exist (v0.1.33 was the version available when daemon.node was written). Now there is a native way to fork, so this should no longer be necessary. (Plus, it appears to have been abandoned too.)
child_process.fork() has a totally misleading name and is not the same as C’s fork().
According to the docs, it executes a Node.js script as a child process and sets up a communications channel between the calling process and the child. That's it.
The actual spawning of the child process is done inside libuv, Node's “platform layer,” in C, and fork() itself is not exposed to Node scripts.
A simple, much-improvable way to daemonize using only what’s built-in to Node.js might look like this:
if (process.argv[2] !== 'child') {
require('child_process').execFile(process.argv[0], [__filename, 'child']);
process.exit();
}
setTimeout(function(){
console.log('foo');
}, 5000);
Obviously, this is pretty different from fork(). If daemon.node works for you, keep using it.
daemon.node continues to be developed at https://github.com/indexzero/daemon.node.

Categories

Resources