search by cht nodejs Chinese to unicode
and get below info:
function convert(s) {
return s.split('').map(function(c) {
return '\\u' + ('0000' + c.charCodeAt(0).toString(16).toUpperCase()).slice(-4);
}).join('');
}
var s = '字符串';
s="time out"
const encodeStr = convert(s)
console.log(encodeStr);
refactor the function to my tool js and quick test the selected content in vscode by "ctrl+alt+n" shortcut provided by Code Runner
const unicodeencode = originalStr => {
return originalStr
.split("")
.map(c => {
return (
"\\u" +
(
"0000" +
c
.charCodeAt(0)
.toString(16)
.toUpperCase()
).slice(-4)
);
})
.join("");
};
const unicodeEncodeTest = inputStr => {
let s = "字符串";
let encodeStr = unicodeencode(s);
console.log(encodeStr);
s = "time out";
encodeStr = unicodeencode(s);
console.log(encodeStr);
};
// unicodeEncodeTest();
now use it in my nodejs cli tool
27617 $ cli --ue wode
{ unicodeencode: 'wode' }
2019-10-17T07:39:28.850Z npmCli key:unicodeencode, value: wode
2019-10-17T07:39:28.850Z npmCli \u0077\u006F\u0064\u0065
the cli configuration is as simple as adding one option now (since I have make it auto call any function name)
.option("--ue, --unicodeencode [word]", "unicodeencode the string")
here comes the incredible way to make nodejs cli tool auto call any function provided by tool js
const program = require("commander");
....
//filter the program object key to find the user input ones via cli
const checkin = _(program)
.pickBy((v, p) => {
return (v === true || _.isString(v)) && !/^_/gi.test(p);
})
.value();
//if user input cli option name matches any function name in tool js, then call it
} else if (!_.isEmpty(checkin)) {
_(checkin).forIn((value, key) => {
cli.debug(`key:${key}, value: ${value}`);
clicmd = cli[key];
const result = clicmd(value);
if (result) cli.debug(result);
});
} else {
program.outputHelp();
process.exit(1);
}
网友评论