Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

node.js - How can I run front end Javascript files with node?

I often times find myself wanting to run simple frontend javascript files with node for testing. however node does not understand document, and is not able to access elements in my html. Is there a way to add this functionality or otherwise run frontend js files?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In today's world, you pick an environment that contains the Javascript interpreter and then you can program, not only using what is built into the Javascript language, but also what other capabilities are built into that specific environment. In your case, the browser environment is where things like window and document come from. So, to program with those objects, you need a Javascript environment that supports those objects. Those objects are not built into the Javascript language itself - they are part of the browser environment.

node.js is also a Javascript environment, but it comes with a different set of APIs that do not include window and document, but it does include all sorts of things that the browser environment does not include such as the modules for http, net, streams, fs, etc...

So, if you wanted to run code designed for a browser in node.js, you would have to get a browser simulator (a library that makes the browser-specific things available so you can run them in nodejs such as puppeteer) - it uses the Chromium engine from Google to make browser functionality available from nodejs. If what you're trying to do is to test web page Javascript, then it may be easiest to use a program specifically designed for testing web page Javascript from nodejs such as Mocha.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...