要求没有定义?节点.js [英] require is not defined? Node.js

查看:22
本文介绍了要求没有定义?节点.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始使用 Node.js.在我的 app/js 文件中,我正在做这样的事情:

Just started working with Node.js. In my app/js file, I am doing something like this:

app.js

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Am I really running a server?!');
}).listen(8080, '127.0.0.1');

console.log('running server!');

当我在我的终端中运行 node app.js 时,控制台会吐出 'running server!',但在我的浏览器中我得到,未捕获的引用错误:未定义要求.

When I'm in my terminal and run node app.js, the console spits out 'running server!', but in my browser I get, Uncaught ReferenceError: require is not defined.

有人可以向我解释为什么在终端中它可以正常工作,但在浏览器中却不能吗?

Can someone explain to me why in the terminal, it works correctly but in the browser, it doesn't?

我正在使用节点的 http-server 来为我的页面提供服务.

I am using the node's http-server to serve my page.

推荐答案

在终端中,您正在运行节点应用程序,它正在运行您的脚本.这是一个与在浏览器中直接运行脚本截然不同的执行环境.虽然 Javascript 语言大致相同(如果您运行的是 Chrome 浏览器,则两者都是 V8),但其余的执行环境(例如可用的库)并不相同.

In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.

node.js 是一个服务器端 Javascript 执行环境,它结合了 V8 Javascript 引擎和一堆服务器端库.require() 就是 node.js 添加到环境中的一种特性.因此,当您在终端中运行 node 时,您正在运行一个包含 require() 的环境.

node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().

require() 不是浏览器内置的功能.这是 node.js 的一个特定特性,而不是浏览器的特性.因此,当您尝试让浏览器运行您的脚本时,它没有 require().

require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().

有多种方法可以在浏览器中运行某些形式的 node.js 代码(但不是全部).例如,您可以获得 require() 的浏览器替代品,它们的工作方式类似(尽管不完全相同).

There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require() that work similarly (though not identically).

但是,您不会在浏览器中运行 Web 服务器,因为浏览器无法执行此操作.

But, you won't be running a web server in your browser as that is not something the browser has the capability to do.

您可能对 browserify 感兴趣,它允许您使用 require() 在浏览器中使用节点样式模块声明.

You may be interested in browserify which lets you use node-style modules in a browser using require() statements.

这篇关于要求没有定义?节点.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆