I want to write some command with some args (for example /add 5 5 and it will print 10) in console when program is already running. How should I do it?
How to read from console is already explained in this answer, so I'll just show you how to parse those lines.
Example approach is to create object with references to your functions, and then call them by name, after parsing input string.
My example uses Spread Operator and let which need running script in strict mode ( "use strict"; ).
Example's code:
"use strict";
var funs = {};
funs.add = function add (x, y) {
if( x === undefined || y === undefined ) {
console.log("Not enough arguments for add!");
return;
}
console.log("Result:", (+x) + (+y));
}
function parseInput(input) {
if( input.charAt(0) === "/" ) {
let tmp = input.substring(1);
tmp = tmp.split(" ");
let command = tmp[0];
let args = tmp.slice(1);
let fun = funs[command];
if ( fun === undefined ) {
console.log(command, "command is not defined!");
return;
}
fun(...args);
}
}
parseInput("/add 5 6");
The following npm packages could help you a lot, and their docs are very great to start with:
https://www.npmjs.com/package/comman
https://www.npmjs.com/package/prompt
Related
Okay so, I npm run build my application, drag the build files into tizon studio.
Run the application...
I get the error:
2.bd938b3f.chunk.js:79798 Uncaught TypeError: Object.values is not a function
The same behavior is shown on any Samsung and Tizon model I've tested this on.
I've tried switching out Object.values with Object.map,
which returns "the same" error.
2.bd938b3f.chunk.js:79798 Uncaught TypeError: Object.map is not a function
I have not been able to find an answer to fix this.
Any help with finding an answer would be massively appreciated.
Thank you all in advance!
if (!le) {
(function () {
for (var e = window.document.getElementsByTagName("script"), t = 0, n = Object.values(e); t < n.length; t++) {
var r = n[t];
if (r.src && r.src.includes(te))
return r
}
return null
})() || function (e) {
var t = document.createElement("script");
t.src = te + "?l=" + e,
t.async = !0,
document.head.appendChild(t)
}
(ue),
function (e) {
var t = [];
Array.isArray(window[e]) ? t = window[e] : window[e] = t
}
(ue);
var r = ne(se, ue, ce),
i = r.wrappedGtag,
a = r.gtagCore;
ie = i,
re = a,
le = !0
}
Samsung's TizenOS's javascript isn't as up-to-date as it could be, and according to this looks to not be actively supported.
You can use react-app-polyfill to provide any missing functionalities.
We use the following in our root index.jsx as the "kitchen sink" of polyfills
import 'react-app-polyfill/ie9';
import 'react-app-polyfill/stable';
It seems Object.values() is not supported in your developing environment. Try adding this polyfill on top of your script file: https://github.com/tc39/proposal-object-values-entries/blob/master/polyfill.js
You can define your own values function if the node version is too low.
if (!Object.values) {
Object.values = function values(O) {
return Object.keys(O).map(k=>O[k]);
};
}
I was watching a course that showed how to make an console.log with custom configs, like the color or depending on your env mode, you show the log or not.
But i keep getting the error TypeError: Converting circular structure to JSON
and I don't know why this is happening and how to solve it.
In the course, that works fine, but it doesn't to me.
node version => v8.11.2
require('colors')
const _ = require('lodash')
const config = require('../config/config')
const noop = () => { }
const consoleLog = config.logging ? console.log.bind(console) : noop
const logger = {
log: () => {
const args = _.toArray(arguments)
.map(arg => {
if (typeof arg === 'object') {
let str = JSON.stringify(arg, 2)
return str.magenta
} else {
arg += ''
return arg.magenta
}
})
consoleLog.apply(console, args)
}
}
module.exports = logger
Edit1: arguments can be anything, since logger will be used to log things with different colors in the console.
logger.log('some thing you want to log')
logger.log() is an arrow function, so arguments are not arguments of this function (see Arrow functions: No binding of arguments), but arguments of a parent function, in this case — Node.js wrapper function that compiles modules and has arguments with circular dependencies.
Try to use common function here:
const logger = {
log() {
// ...
}
};
I'm writing a plugin for Brunch to 'filter' files from code library. Basic idea is to:
check my source files (in src\ folder, or any watched folders that don't match library pattern),
build a list of imported/required modules from code library (in lib\ folder, outside src\, somewhere on disk)
check files against this list and 'approve' or 'reject' them
compile only what's 'approved', so I don't end up with huge files that have all modules/components from my library, but only what I use in particular project
When I work only with JavaScript files this.pattern = /.*(js|jsx)$/; everything works fine. Next step is to include more files, since many modules/components in library have some sort of template or stylesheets, for example this is one AngularJS module:
lib\
modules\
pager\
controller.jsx
directive.jsx
template.html
pager.styl
README.md
But when I expand the pattern to include other files this.pattern = /.*/;, I run into all sorts of issues (; Most have to do with pipline - those are the kinds of errors I'm getting. For example:
jshint-brunch doesn't like README.md
html-brunch won't wrap template.html
stylus-brunch and sass-brunch are also unhappy
I've tried solving these problems individually, for example if I disable html-brunch config.plugins.off: ['html-brunch'], and add this code inside the compiler function, it kinda works:
if( params.path.match(/.html$/) ) {
params.data = "module.exports = function() { return " + JSON.stringify(params.data) + ";};";
return callback(null, this.config.modules.wrapper(params.path, params.data));
}
..but I couldn't resolve all the issues. Pretty much all problems have to do with this line in the compiler function: return callback(null, null);. When I 'reject' a file next plugin gets something undefined and breaks...
Any ideas how to solve this?
I'd like to eventually expand plugin's functionality to handle static assets too, for example copy lib\images\placeholder-1.jpg (but not placeholder-2.jpg) from library if it's used in html files, but I'm stuck at this point...
Here's the code of the plugin:
var CodeLibrary;
module.exports = CodeLibrary = (function() {
var required = [];
CodeLibrary.prototype.brunchPlugin = true;
function CodeLibrary(config) {
this.config = config;
this.pattern = /.*/;
this.watched = this.config.paths.watched.filter(function(path) {
return !path.match( config.plugins.library.pattern );
});
}
function is_required(path) {
var name = this.config.modules.nameCleaner(path);
return required.some(function(e, i, a) { return name.match(e); });
}
function in_library(path) {
return Boolean(path.match( this.config.plugins.library.pattern ));
}
function is_watched(path) {
return this.watched.some(function(e, i, a) { return path.match( e ); });
}
CodeLibrary.prototype.lint = function(data, path, callback) {
if( !is_watched.apply(this, [path]) &&
!is_required.apply(this, [path]) )
return callback();
var es6_pattern = /import .*'(.*)'/gm;
var commonjs_pattern = /require\('(.*)'\)/gm;
var match = es6_pattern.exec(data) || commonjs_pattern.exec(data);
while( match != null ) {
if( required.indexOf(match[1]) === -1 )
required.push( match[1] );
match = es6_pattern.exec(data) || commonjs_pattern.exec(data);
}
callback();
}
CodeLibrary.prototype.compile = function(params, callback) {
if( is_required.apply(this, [params.path]) ||
!in_library.apply(this, [params.path]) )
return callback(null, params);
return callback(null, null);
};
return CodeLibrary;
})();
ReferenceError: documentGetElementsByName is not defined
MoveSiteTitle();
ReferenceError: MoveSiteTitle is not defined
MoveSiteTitle();
Any help ....!
Well, seems to be a Chrome related issue as df1 reported. There is one solution however to get rid of the script error if you like.
Put this code inside your master page above the s4-workspace tag or similar:
if(typeof documentGetElementsByName==='undefined')
{
documentGetElementsByName = function(value){
if($('[name="'+value+'"]'))
{
return $('[name="'+value+'"]');
}
return null;
};
}
if(typeof MoveSiteTitle==='undefined')
{
// Well.... Don't know what this function is supposed to do
// but this way I am avoiding script error...
MoveSiteTitle = function(value){
return "";
};
}
This is just javascript basic error.Here documentGetElementsByName(What is the variable name here) Check this variable name and search cant find any where in ur current page. Modify variable name or put some condition over there.
The problem is that something in your configuration is causing the script that contains the method MoveSiteTitle() to not load.
I was able to obtain the source for the method "MoveSiteTitle" from my dev tools console. You could alter your master page to include the following JavaScript in the <head> section of the master page.
if (typeof MoveSiteTitle === 'undefined') {
function MoveSiteTitle() {
a:;
var b = documentGetElementsByName("titlewpTitleArea");
if (b == null || b[0] == null) return;
var a = b[0],
c = documentGetElementsByName("onetidProjectPropertyTitle");
if (c == null || c[0] == null) return;
var e = c[0],
d = document.getElementById("onetidPageTitleSeparator");
if (d == null) return;
if (Boolean(a.insertAdjacentElement)) {
a.insertAdjacentElement("afterBegin", d);
a.insertAdjacentElement("afterBegin", e)
} else {
a.insertBefore(d, a.firstChild);
a.insertBefore(e, a.firstChild)
}
}
}
Also, I found the MoveSiteTitle method (for Sharepoint 2013) in the following file within the hive (hive 15).
V:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\IE55UP.js
You might be able to debug your specific configuration from there.
Also, the script for GetElementsByName is...
function GetElementsByName(b) {
var a = document.getElementsByName(b);
if (a.length == 0 && Boolean(window.XMLHttpRequest)) a = FFGetElementsById(document, b);
return a
}
argparse for python makes it quick and easy to handle command-line input, handling positional arguments, optional arguments, flags, input validation and much more. I've started writing applications in node.js and I'm finding it tedious and time consuming to write all that stuff manually.
Is there a node.js module for handling this?
There is one direct port, conveniently also called argparse.
There are a slew of various command line argument handlers at https://github.com/joyent/node/wiki/modules#wiki-parsers-commandline
The one I use in most projects is https://github.com/visionmedia/commander.js though I would take a look at all of them to see which one suits your specific needs.
In 18.3.0 nodejs has landed a core addition util.parseArgs([config])
Detailed documentation is available here: https://github.com/pkgjs/parseargs#faqs
There's yargs, which seems to be pretty complete and well documented.
Here is some simple boilerplate code which allows you to provide named args:
const parse_args = () => {
const argv = process.argv.slice(2);
let args = {};
for (const arg of argv){
const [key,value] = arg.split("=");
args[key] = value;
}
return args;
}
const main = () => {
const args = parse_args()
console.log(args.name);
}
Example usage:
# pass arg name equal to monkey
node arg_test.js name=monkey
# Output
>> monkey
You can also add a Set of accepted names and throw exception if an invalid name is provided:
const parse_args = (valid_args) => {
const argv = process.argv.slice(2);
let args = {};
let invalid_args = [];
for (const arg of argv){
const [key,value] = arg.split("=");
if(valid_args.has(key)){
args[key] = value;
} else {
invalid_args.push(key);
}
}
if(invalid_args.length > 0){
throw new Exception(`Invalid args ${invalid_args} provided`);
}
return args;
}
const main = () => {
const valid_args = new Set(["name"])
const args = parse_args(valid_args)
console.log(args.name);
}