Issue with starting appium server programatically in Java on Windows

I am facing an issue when trying to create an appium server programmatically using Java. Below is the code snippet:
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
import io.appium.java_client.service.local.flags.GeneralServerFlag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map; 
import java.io.File;
import java.util.concurrent.TimeUnit;


public class AppiumStartServer {
    private final static Logger log = LoggerFactory.getLogger(AppiumStartServer.class);
    private static AppiumDriverLocalService service = null;


    private AppiumStartServer() {
    }

    public static AppiumDriverLocalService getService() {
        if (service == null) {
            initAppiumService();
        }
        if (service == null) {
            System.out.println("Cannot start Appium Driver Local Service.");
        }
        return service;
    }

    private static void initAppiumService() {
        Map<String, String> env = new HashMap<>(System.getenv());
        env.put("PATH", "/usr/local/bin:" + env.get("PATH"));
        env.put("ANDROID_HOME", "C:/Users/user_name/AppData/Local/Android/Sdk");

        service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
            .usingAnyFreePort()
            .withAppiumJS(new File("C:\\Users\\user_name\\AppData\\Roaming\\npm\\node_modules\\appium\\lib\\main.js"))
            .usingDriverExecutable(new File("C:\\Program Files\\nodejs\\node.exe"))
            .withArgument(GeneralServerFlag.SESSION_OVERRIDE)
            .withArgument(GeneralServerFlag.LOG_LEVEL, "error")
            .withArgument(GeneralServerFlag.RELAXED_SECURITY)
            .withEnvironment(env)
            .withLogFile(new File("target/appium.log"))
            .withStartUpTimeOut(60, TimeUnit.SECONDS));

        log.info("New Appium service: " + service.getUrl());
        service.start();
    }

    public static void main(String[] args){
        getService();
    }
}

Environment details:
OS: Windows 10;
Node version: v16.5.0
Appium version: 1.21.0
Java: Open JDK8
Logs:
(node:27752) Warning: To load an ES module, set “type”: “module” in the package.json or use the .mjs extension.
(Use node --trace-warnings ... to show where the warning was created)
C:\Users\ratan.masanta\AppData\Roaming\npm\node_modules\appium\lib\main.js:4
import { init as logsinkInit, clear as logsinkClear } from ‘./logsink’;
^^^^^^

SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1025:15)
at Module._compile (node:internal/modules/cjs/loader:1059:27)
at Object.Module._extensions…js (node:internal/modules/cjs/loader:1124:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:816:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47
Exception in thread “main” io.appium.java_client.service.local.AppiumServerHasNotBeenStartedLocallyException: The local appium server has not been started. The given Node.js executable: C:\Program Files\nodejs\node.exe Arguments: [C:\Users\ratan.masanta\AppData\Roaming\npm\node_modules\appium\lib\main.js, --port, 39062, --address, 0.0.0.0, --log, D:\ws-scrcpy-master-shashikant\ws-scrcpy-master (1)\PP_SGT\target\appium.log, --log-level, error, --relaxed-security, --session-override]
Process output: (node:27752) Warning: To load an ES module, set “type”: “module” in the package.json or use the .mjs extension.
(Use node --trace-warnings ... to show where the warning was created)
C:\Users\ratan.masanta\AppData\Roaming\npm\node_modules\appium\lib\main.js:4
import { init as logsinkInit, clear as logsinkClear } from ‘./logsink’;
^^^^^^

SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1025:15)
at Module._compile (node:internal/modules/cjs/loader:1059:27)
at Object.Module._extensions…js (node:internal/modules/cjs/loader:1124:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:816:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47

at io.appium.java_client.service.local.AppiumDriverLocalService.start(AppiumDriverLocalService.java:168)
at AppiumStartServer.initAppiumService(AppiumStartServer.java:48)
at AppiumStartServer.getService(AppiumStartServer.java:23)
at AppiumStartServer.main(AppiumStartServer.java:52)

Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://127.0.0.1:39062/wd/hub/status] to be available after 60010 ms
at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
at io.appium.java_client.service.local.AppiumDriverLocalService.ping(AppiumDriverLocalService.java:133)
at io.appium.java_client.service.local.AppiumDriverLocalService.start(AppiumDriverLocalService.java:155)
… 3 more
Caused by: java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask.get(FutureTask.java:205)
at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:156)
at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
… 5 more

Please help me in fixing this issue as it’s breaking my fuction.

Can you start appium with simple command in command prompt on Windows:

appium

?

It looks like you are providing a wrong path to the Appium’s main script. The correct one must be located in build/lib subfolder.

Yes. It starts with the normal appium command.

Thanks for the help. This resolved the issue.