简体   繁体   English

nodejs看不到已安装的mysql模块

[英]nodejs cannot see installed mysql module

I'm trying to install the mysql module for nodejs using npm. 我正在尝试使用npm为nodejs安装mysql模块。 I'm using the windows subsystem for linux to do this. 我使用Linux的Windows子系统来执行此操作。 I've successfully installed using: 我已成功使用以下工具安装:

sudo npm install -g mysql

My console returns: 我的控制台返回:

+ mysql@2.16.0
added 11 packages from 15 contributors in 5.779s

However, when importing the module using: 但是,使用以下命令导入模块时:

const mysql = require("mysql"); 

I receive the error: 我收到错误:

module.js:550
    throw err;
    ^

Error: Cannot find module 'mysql'
    at Function.Module._resolveFilename (module.js:548:15)
    at Function.Module._load (module.js:475:25)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/mnt/c/Users/alesi/Documents/coding/Web/Portfolio/src/servers/server.js:7:15)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)

Other modules such as querystring and nodemailer work just fine. 其他模块,例如querystring和nodemailer都可以正常工作。 Any ideas? 有任何想法吗?

When you install a package globally, the package is usually installed in %USERPROFILE%\\AppData\\Roaming\\npm\\node_module on windows or /usr/local/lib/node_modules in unix systems. 在全局范围内安装软件包时,该软件包通常安装在Windows上的%USERPROFILE%\\AppData\\Roaming\\npm\\node_module或unix系统中的/usr/local/lib/node_modules中。 See this post. 看到这篇文章。

Now in your project, when you require() something, it is looking to the current directory's node_modules folder. 现在在您的项目中,当您require() ,它将查找当前目录的node_modules文件夹。 Because you installed the package globally, it does not exist in the project. 因为您是全局安装的软件包,所以项目中不存在该软件包。

Running this will download the package to your project's node_modules folder, instead of global node_modules . 运行此命令会将包下载到项目的 node_modules文件夹中,而不是全局 node_modules --save will also write it as a dependency to package.json --save还将其写为package.json的依赖项

npm install --save mysql

In my experience, global packages seem to be used for CLI's or running scripts from command prompt, and not for using in code. 以我的经验,全局软件包似乎用于CLI或从命令提示符运行的脚本,而不用于代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM