Node.js项目启动时出现TypeError: mode must be int32 or null/undefined错误求助
Node.js项目启动时出现TypeError: mode must be int32 or null/undefined错误求助
问题描述
我有一个Node.js项目,结构如下:
api swagger.yaml - having visual representation of the API and its documentation controllers entityApi.js file - APIs - create,delete,list,patch api service entityService.js - API implementation utils mongoUtils.js index.js file .... and other files
npm install执行正常,但运行node index.js时出现以下错误:
binding.copyFile( ** ^ TypeError: mode must be int32 or null/undefined at Object.copyFileSync (node:fs:3086:11) at Object.<anonymous> (C:\Users\shivashankar.g02\<<project path>>\index.js:18:4) at Module._compile (node:internal/modules/cjs/loader:1562:14) ** at Object..js (node:internal/modules/cjs/loader:1699:10) at Module.load (node:internal/modules/cjs/loader:1313:32) at Function._load (node:internal/modules/cjs/loader:1123:12) at TracingChannel.traceSync (node:diagnostics_channel:322:14) at wrapModuleLoad (node:internal/modules/cjs/loader:217:24) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:170:5) at node:internal/main/run_main_module:36:49 { code: 'ERR_INVALID_ARG_TYPE'
index.js中触发错误的代码片段:
//error is coming here fs.copyFileSync(path.join(__dirname, './index.html_replacement'), path.join(__dirname, './node_modules/swagger-ui-dist/index.html'), (err) => { if(err) { console.log('Unable to replace swagger-ui-dist/index.html file - something wrong with the installation ??'); process.exit(1); } })
请问这个错误是什么原因导致的?有什么解决办法?
解决方案
这个错误的根源很明确——你混淆了Node.js fs模块的同步与异步方法!
fs.copyFileSync是同步文件复制方法,它的参数定义是:
fs.copyFileSync(src, dest[, mode])
第三个可选参数是mode(整数类型,用于指定文件权限),可以不传、传null或undefined,但它完全不支持回调函数。你把回调函数当成第三个参数传递,Node.js会把这个函数误判为mode参数,类型不匹配自然抛出ERR_INVALID_ARG_TYPE错误。
修复方法一:使用同步方法的错误处理(推荐,适合启动阶段操作)
用try/catch包裹同步操作来捕获错误:
try { // 移除错误的回调参数 fs.copyFileSync( path.join(__dirname, './index.html_replacement'), path.join(__dirname, './node_modules/swagger-ui-dist/index.html') ); } catch (err) { console.log('Unable to replace swagger-ui-dist/index.html file - something wrong with the installation ??'); process.exit(1); }
修复方法二:改用异步方法fs.copyFile
如果你更倾向于异步操作,应该使用不带Sync后缀的fs.copyFile,它才接受回调函数作为第三个参数:
fs.copyFile( path.join(__dirname, './index.html_replacement'), path.join(__dirname, './node_modules/swagger-ui-dist/index.html'), (err) => { if(err) { console.log('Unable to replace swagger-ui-dist/index.html file - something wrong with the installation ??'); process.exit(1); } // 注意:需要把后续的swaggerTools初始化等逻辑移到这里,避免异步顺序问题 } )
不过因为这是项目启动时的必要文件替换操作,用同步方法更稳妥,能确保文件替换完成后再启动服务器。
备注:内容来源于stack exchange,提问作者user1876040
相关产品推荐
相关产品推荐

