简体   繁体   English

从JavaScript(浏览器)启动Node.js文件/模块

[英]Start a Node.js file/module from JavaScript (browser)

Is it possible to run a Node.js file from the serverside from JavaScript? 是否可以从JavaScript从服务器端运行Node.js文件? If so how would i? 如果可以,我该怎么办? I have googled some but cant find a real answer to this. 我已经用谷歌搜索了一些,但是找不到真正的答案。 Thanks 谢谢

如果此文件使用Nodejs API(例如Streams,HTTP,File System等) ,则不可能,因为浏览器无法运行这些API。

there are some basic differences between browser js env and node server env. 浏览器js env和节点服务器env之间有一些基本区别。 Example: WEB API is availble for browser js env for node its different. 示例:WEB API对于不同的节点可用于浏览器js env。

Moreover node ecosystem has alot more support for several other functinalities like file system handling etc. 此外,节点生态系统还对其他几个功能(如文件系统处理等)提供了更多支持。

Since node is developed for server side programming,you should pay proper respect to the purpose and not try to run it in browser :) 由于node是为服务器端编程而开发的,因此您应该充分注意此目的,而不要尝试在浏览器中运行它:)

NodeJS is JavaScript on the server-side environment. NodeJS是服务器端环境中的JavaScript。

What you refer as "JavaScript" is actually the same JavaScript, just in your browser environment. 您所说的“ JavaScript”实际上是相同的JavaScript,只是在您的浏览器环境中。

What you can do: you can use Webpack to create a NodeJS app, that will automatically create an index.html and put it on a server. 您可以做什么:您可以使用Webpack创建NodeJS应用程序,该应用程序将自动创建index.html并将其放置在服务器上。 With webpack, you can also import NodeJS modules in your frontend code. 使用webpack,您还可以在前端代码中导入NodeJS模块。

For example: 例如:

main.js: main.js:

import './index.html';
import $ from 'jquery';

$(() => {
    console.log('jquery is ready');
    $('#root').append('<h2>How are you doing?</h2>');
});

index.html: index.html的:

<html>
    <head>
    </head>
    <body>
        <div id="root"></div>
        <script src="bundle.js"></script>
    </body>
</html>

The bundle.js will be generated by Webpack. bundle.js将由Webpack生成。

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

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