chore: add nodejs install initialize

This commit is contained in:
ihmily 2024-10-23 13:32:58 +08:00
parent a9b95cc491
commit e1cce5c0f1
3 changed files with 47 additions and 30 deletions

View File

@ -1,5 +1,14 @@
import os
import sys
from pathlib import Path
from .initializer import check_node
current_file_path = Path(__file__).resolve()
current_dir = current_file_path.parent
JS_SCRIPT_PATH = current_dir / 'javascript'
execute_dir = os.path.split(os.path.realpath(sys.argv[0]))[0]
node_execute_dir = Path(execute_dir) / 'node'
current_env_path = os.environ.get('PATH')
os.environ['PATH'] = str(node_execute_dir) + os.pathsep + current_env_path
check_node()

View File

@ -10,6 +10,8 @@ import os
import subprocess
import sys
import platform
import zipfile
from pathlib import Path
import requests
import re
import distro
@ -17,6 +19,16 @@ from tqdm import tqdm
from .logger import logger
current_platform = platform.system()
execute_dir = os.path.split(os.path.realpath(sys.argv[0]))[0]
current_env_path = os.environ.get('PATH')
def unzip_file(zip_path, extract_to):
if not os.path.exists(extract_to):
os.makedirs(extract_to)
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(extract_to)
def install_nodejs_windows():
@ -25,18 +37,20 @@ def install_nodejs_windows():
logger.debug("Installing the stable version of Node.js for Windows...")
response = requests.get('https://nodejs.cn/download/')
if response.status_code == 200:
match = re.search('href="(https://npmmirror.com/mirrors/node/v.*?/node-v.*?.msi)"> <svg class="d',
match = re.search('https://npmmirror.com/mirrors/node/(v.*?)/node-(v.*?)-x64.msi',
response.text)
if match:
url = match.group(1)
version = url.rsplit('/', maxsplit=2)[1]
version = match.group(1)
system_bit = 'x64' if '32' not in platform.machine() else 'x86'
url = f'https://npmmirror.com/mirrors/node/{version}/node-{version}-win-{system_bit}.zip'
else:
logger.error("Failed to retrieve the download URL for the latest version of Node.js...")
return
temp_dir = os.path.split(os.path.realpath(sys.argv[0]))[0]
file_path = os.path.join(temp_dir, url.rsplit('/', maxsplit=1)[-1])
if os.path.exists(file_path):
full_file_name = url.rsplit('/', maxsplit=1)[-1]
zip_file_path = Path(execute_dir) / full_file_name
if Path(zip_file_path).exists():
logger.debug("Node.js installation file already exists, start install...")
else:
response = requests.get(url, stream=True)
@ -45,23 +59,29 @@ def install_nodejs_windows():
with tqdm(total=total_size, unit="B", unit_scale=True,
ncols=100, desc=f'Downloading Node.js ({version})') as t:
with open(file_path, 'wb') as f:
with open(zip_file_path, 'wb') as f:
for data in response.iter_content(block_size):
t.update(len(data))
f.write(data)
powershell_command = f"Start-Process 'msiexec' -ArgumentList '/i {file_path} /quiet' -Wait -NoNewWindow"
result = subprocess.run(["powershell", "-Command", powershell_command], capture_output=True, text=True)
if result.returncode == 0:
logger.debug('Node.js installation was successful. Restart for changes to take effect.')
unzip_file(zip_file_path, execute_dir)
extract_dir_path = str(zip_file_path).rsplit('.', maxsplit=1)[0]
f_path, f_name = os.path.splitext(zip_file_path)
new_extract_dir_path = Path(f_path).parent / 'node'
if Path(extract_dir_path).exists() and not Path(new_extract_dir_path).exists():
os.rename(extract_dir_path, new_extract_dir_path)
os.environ['PATH'] = execute_dir + '/node' + os.pathsep + current_env_path
result = subprocess.run(["node", "-v"], capture_output=True)
if result.returncode == 0:
logger.debug('Node.js installation was successful. Restart for changes to take effect')
else:
logger.debug('Node.js installation failed')
return True
else:
logger.error("Node.js installation failed")
else:
logger.error("Failed to retrieve the stable Node.js version page")
logger.error("Failed to retrieve the Node.js version page")
except Exception as e:
logger.error(f"type: {type(e).__name__}, Node.js installation failed")
logger.error(f"type: {type(e).__name__}, Node.js installation failed {e}")
def install_nodejs_centos():
@ -184,6 +204,5 @@ def check_nodejs_installed():
def check_node():
res = check_nodejs_installed()
if not res:
if not check_nodejs_installed():
return install_nodejs()

View File

@ -4,15 +4,12 @@ import os
import functools
import hashlib
import re
import time
import traceback
from typing import Union, Any
import execjs
from .logger import logger
import configparser
is_install_node = False
def trace_error_decorator(func: callable) -> callable:
@functools.wraps(func)
@ -20,15 +17,7 @@ def trace_error_decorator(func: callable) -> callable:
try:
return func(*args, **kwargs)
except execjs.ProgramError:
global is_install_node
if not is_install_node:
is_install_node = True
logger.warning('Failed to execute JS code. Please check if the Node.js environment')
from .initializer import check_node
is_install_node = check_node()
if is_install_node:
time.sleep(3)
os._exit(0)
logger.warning('Failed to execute JS code. Please check if the Node.js environment')
except Exception as e:
error_line = traceback.extract_tb(e.__traceback__)[-1].lineno
error_info = f"错误信息: type: {type(e).__name__}, {str(e)} in function {func.__name__} at line: {error_line}"
@ -119,4 +108,4 @@ def remove_emojis(text, replace_text=r''):
"]+",
flags=re.UNICODE
)
return emoji_pattern.sub(replace_text, text)
return emoji_pattern.sub(replace_text, text)