You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
use std::fs::File;use std::io::{self,BufRead,BufReader};use clap::{Arg,Command};use deno_core::JsRuntime;use deno_core::RuntimeOptions;// use deno_core::serde_v8;use deno_core::v8;fnmain(){// 定义参数形式为 jtxt [option] function [file]let matches = Command::new("jtxt").version("1.0").author("Your Name <sunwu51@126.com>").about("Processes lines of input with JavaScript").arg(Arg::new("begin").short('b').long("begin").help("JavaScript code to execute before processing any lines").value_parser(clap::builder::ValueParser::string())).arg(Arg::new("end").short('e').long("end").help("JavaScript code to execute after processing all lines").value_parser(clap::builder::ValueParser::string())).arg(Arg::new("function").help("JavaScript code to process each line, l is the origin string").required(true).index(1)).arg(Arg::new("file").help("Path to the input file. If not provided, reads from stdin.").index(2)).get_matches();let begin_code = matches.get_one::<String>("begin");let end_code = matches.get_one::<String>("end").cloned();let js_function = matches.get_one::<String>("function").unwrap();let file_path = matches.get_one::<String>("file");// 创建JavaScript 执行上下文letmut runtime = JsRuntime::new(RuntimeOptions::default());// 创建全局变量
runtime.execute_script("<anon>","var ctx = {}, n1=0, n2=0, n3=0, s='', arr=[];").expect("Eval failed");// 执行begin的代码块,如果有的话ifletSome(code) = begin_code {
runtime.execute_script("<anon>", code.to_string()).expect("Eval failed");}// 逐行读取文件或者管道内容let input:Box<dynBufRead> = ifletSome(path) = file_path {Box::new(BufReader::new(File::open(path).expect("Failed to open file")))}else{Box::new(io::stdin().lock())};
runtime.execute_script("<anon>",format!("function process(){{ {} }}", js_function)).expect("Eval failed");for line in input.lines(){let line = line.unwrap();{// 创建一个 V8 值let scope = &mut runtime.handle_scope();let value = v8::String::new(scope,&line).unwrap();// 将 V8 值绑定到全局对象let global = scope.get_current_context().global(scope);let l = v8::String::new(scope,"l").unwrap().into();
global.set(scope, l, value.into());}
runtime.execute_script("<anon>","process()").expect("Eval failed");}ifletSome(code) = end_code {
runtime.execute_script("<anon>", code).expect("Eval failed");}}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
https://www.xiaogenban1993.com/blog/24.10/js%E8%AF%AD%E6%B3%95%E7%9A%84awk
Generated by FreeCoder
https://www.xiaogenban1993.com/blog/24.10/js%E8%AF%AD%E6%B3%95%E7%9A%84awk
Beta Was this translation helpful? Give feedback.
All reactions