nodejs的切换commonjs和esmodule语法

package.json里修改type:

json 复制代码
{
	...
	"type": "commonjs",//commonjs语法
	"type": "module",//esmodule语法
	...
}

commonjs语法:

CommUtils.js文件:

javascript 复制代码
const fs = require('fs');

function readJsonFile(filePath) {
    try {
        const data = fs.readFileSync(filePath, 'utf-8');
        return JSON.parse(data);
    } catch (error) {
        // 处理读取文件或解析 JSON 错误
        console.error(`Error reading JSON file ${filePath}: ${error.message}`);
        return null;
    }
}

function writeJsonFile(filePath, data) {
    // 如果data为null,则不写入文件
    if (data === null || data === undefined || (Array.isArray(data) && data.length === 0)) {
        return;
    }

    try {
        const jsonData = JSON.stringify(data, null, 4);
        fs.writeFileSync(filePath, jsonData, 'utf-8');
    } catch (error) {
        // 处理写入文件错误
        console.error(`Error writing JSON file ${filePath}: ${error.message}`);
    }
}


function bytesToInteger(bytes, isBigEndian) {  
    if (bytes.length < 1 || bytes.length > 8) {  
        throw new Error("bytes.length<1||bytes.length>8");  
    }  
  
    let temp = 0;  
  
    if (isBigEndian) {  
        for (let i = 0; i < bytes.length; i++) { // 从低位到高位  
            if (i === 0) {  
                temp = (bytes[i] & 0xFF) << (i * 8);  
            } else {  
                temp = temp | ((bytes[i] & 0xFF) << (i * 8));  
            }  
        }  
    } else {  
        for (let i = bytes.length - 1; i >= 0; i--) { // 从高位到低位  
            if (i === (bytes.length - 1)) {  
                temp = (bytes[i] & 0xFF) << ((bytes.length - i - 1) * 8);  
            } else {  
                temp = temp | ((bytes[i] & 0xFF) << ((bytes.length - i - 1) * 8));  
            }  
        }  
    }  
    return temp;  
}

function toHexString(num){
    return '0x'+num.toString(16).toUpperCase().padStart(2,'0');
}
function listToHexString(arr){
    let str = ''
    for(let i=0;i<arr.length;i++){
        str += toHexString(arr[i]) +(i!=arr.length-1?', ':'')
    }
    return str
}

module.exports = {
    readJsonFile,
    writeJsonFile,
    bytesToInteger,
    toHexString,
    listToHexString,
}

使用:

javascript 复制代码
const path = require('path');
const CommUtils = require(path.join(__dirname, 'CommUtils.js'));
console.log(CommUtils.toHexString(111));

esmodule语法:

CommUtils.js文件:

javascript 复制代码
import { readFileSync, writeFileSync } from 'fs';

function readJsonFile(filePath) {
    try {
        const data = readFileSync(filePath, 'utf-8');
        return JSON.parse(data);
    } catch (error) {
        // 处理读取文件或解析 JSON 错误
        console.error(`Error reading JSON file ${filePath}: ${error.message}`);
        return null;
    }
}

function writeJsonFile(filePath, data) {
    // 如果data为null,则不写入文件
    if (data === null || data === undefined || (Array.isArray(data) && data.length === 0)) {
        return;
    }

    try {
        const jsonData = JSON.stringify(data, null, 4);
        writeFileSync(filePath, jsonData, 'utf-8');
    } catch (error) {
        // 处理写入文件错误
        console.error(`Error writing JSON file ${filePath}: ${error.message}`);
    }
}


function bytesToInteger(bytes, isBigEndian) {  
    if (bytes.length < 1 || bytes.length > 8) {  
        throw new Error("bytes.length<1||bytes.length>8");  
    }  
  
    let temp = 0;  
  
    if (isBigEndian) {  
        for (let i = 0; i < bytes.length; i++) { // 从低位到高位  
            if (i === 0) {  
                temp = (bytes[i] & 0xFF) << (i * 8);  
            } else {  
                temp = temp | ((bytes[i] & 0xFF) << (i * 8));  
            }  
        }  
    } else {  
        for (let i = bytes.length - 1; i >= 0; i--) { // 从高位到低位  
            if (i === (bytes.length - 1)) {  
                temp = (bytes[i] & 0xFF) << ((bytes.length - i - 1) * 8);  
            } else {  
                temp = temp | ((bytes[i] & 0xFF) << ((bytes.length - i - 1) * 8));  
            }  
        }  
    }  
    return temp;  
}

function toHexString(num){
    return '0x'+num.toString(16).toUpperCase().padStart(2,'0');
}
function listToHexString(arr){
    let str = ''
    for(let i=0;i<arr.length;i++){
        str += toHexString(arr[i]) +(i!=arr.length-1?', ':'')
    }
    return str
}

export default {
    readJsonFile,
    writeJsonFile,
    bytesToInteger,
    toHexString,
    listToHexString,
}

使用:

javascript 复制代码
import CommUtils from './CommUtils.js';
console.log(CommUtils.toHexString(111));
相关推荐
洛小豆22 分钟前
深入理解Pinia:Options API vs Composition API两种Store定义方式完全指南
前端·javascript·vue.js
Jokerator26 分钟前
Vue 2现代模式打包:双包架构下的性能突围战
javascript·vue.js
洛小豆32 分钟前
JavaScript 对象属性访问的那些坑:她问我为什么用 result.id 而不是 result['id']?我说我不知道...
前端·javascript·vue.js
超级土豆粉40 分钟前
npm 包 scheduler 介绍
前端·npm·node.js
bug爱好者41 分钟前
原生小程序如何实现跨页面传值
前端·javascript
bug爱好者1 小时前
原生微信小程序最实用的工具函数合集
前端·javascript
3Katrina1 小时前
JS事件机制详解(2)--- 委托机制、事件应用
前端·javascript·面试
code_YuJun1 小时前
从内存角度理解JS代码执行过程
javascript
DoraBigHead1 小时前
【JS三兄弟谁是谁】搞懂 splice、slice、split,只需一杯奶茶的时间!
前端·javascript·面试
国家不保护废物2 小时前
前端存储与后端服务的奇妙冒险:一个Node.js服务器的诞生记(cookie实现用户登入)
前端·javascript·后端