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

人盡茶涼 提交于 2021-02-10 15:52:05

问题


Is it possible to run a Node.js file from the serverside from JavaScript? If so how would i? I have googled some but cant find a real answer to this. Thanks


回答1:


NodeJS is JavaScript on the server-side environment.

What you refer as "JavaScript" is actually the same JavaScript, just in your browser environment.

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. With webpack, you can also import NodeJS modules in your frontend code.

For example:

main.js:

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

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

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.




回答2:


If this file uses nodejs API like Streams, HTTP, File System etc, it is impossible, cause browser is not able to run these API.




回答3:


there are some basic differences between browser js env and node server env. Example: WEB API is availble for browser js env for node its different.

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 :)



来源:https://stackoverflow.com/questions/52289413/start-a-node-js-file-module-from-javascript-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!