diff --git a/pkg/reducer/nodejs.go b/pkg/reducer/nodejs.go index 25ca0a1..9194bd3 100644 --- a/pkg/reducer/nodejs.go +++ b/pkg/reducer/nodejs.go @@ -5,14 +5,23 @@ import ( "fmt" "os" "os/exec" + "path" "regexp" "strings" ) func CreateNodejs(args []string) *exec.Cmd { - cmd := exec.Command("node", "-e", nodejs(args)) + cmd := exec.Command("node", "--input-type=module", "-e", nodejs(args)) + nodePath, exist := os.LookupEnv("NODE_PATH") + if exist { + cmd.Dir = path.Dir(nodePath) + } cmd.Env = os.Environ() cmd.Env = append(cmd.Env, "NODE_OPTIONS=--max-old-space-size=8192") + workingDir, err := os.Getwd() + if err == nil { + cmd.Env = append(cmd.Env, "FX_CMD="+workingDir) + } return cmd } @@ -59,12 +68,15 @@ func nodejs(args []string) string { default: rs += fmt.Sprintf( ` - f = function () + let f = function () { return %v } .call(x) x = typeof f === 'function' ? f(x) : f `, a) } + rs += ` + x = await x +` // Generate a beautiful error message. rs += " } catch (e) {\n" pre, post, pointer := trace(args, i) @@ -74,7 +86,16 @@ func nodejs(args []string) string { ) rs += " }\n" } - return fmt.Sprintf(templateJs, rs) + + fxrc := "" + home, err := os.UserHomeDir() + if err == nil { + b, err := os.ReadFile(path.Join(home, ".fxrc.js")) + if err == nil { + fxrc = "\n" + string(b) + } + } + return fmt.Sprintf(templateJs, fxrc, rs) } var flatMapRegex = regexp.MustCompile("^(\\.\\w*)+\\[]") diff --git a/pkg/reducer/reduce.js b/pkg/reducer/reduce.js index 5589aee..c63373f 100644 --- a/pkg/reducer/reduce.js +++ b/pkg/reducer/reduce.js @@ -1,14 +1,16 @@ -const os = require('os') -const fs = require('fs') -const path = require('path') +import os from 'node:os' +import fs from 'node:fs' +import path from 'node:path' +import {createRequire} from 'node:module' +const require = createRequire(process.cwd()) -try { - require(path.join(os.homedir(), '.fxrc')) -} catch (err) { - if (err.code !== 'MODULE_NOT_FOUND') throw err -} +// .fxrc.js %v void async function () { + if (process.env.FX_CWD) { + process.chdir(process.env.FX_CWD) + } + let buffer = '' process.stdin.setEncoding('utf8') for await (let chunk of process.stdin) {