Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 如何在Node.js和浏览器之间共享代码?(How can I share code between Node.js and the browser?)

I am creating a small application with a JavaScript client (run in the browser) and a Node.js server, communicating using WebSocket.(我正在使用JavaScript客户端(在浏览器中运行)和Node.js服务器创建一个小应用程序,使用WebSocket进行通信。)

I would like to share code between the client and the server.(我想在客户端和服务器之间共享代码。)

I have only just started with Node.js and my knowledge of modern JavaScript is a little rusty, to say the least.(我刚刚开始使用Node.js,至少可以说,我对现代JavaScript的了解有点生疏。) So I am still getting my head around the CommonJS require() function.(所以我仍然围绕CommonJS的require()函数。) If I am creating my packages by using the 'export' object, then I cannot see how I could use the same JavaScript files in the browser.(如果我使用'export'对象创建我的包,那么我无法看到如何在浏览器中使用相同的JavaScript文件。)

I want to create a set of methods and classes that are used on both ends to facilitate encoding and decoding messages, and other mirrored tasks.(我想创建一组在两端使用的方法和类,以便于编码和解码消息,以及其他镜像任务。)

However, the Node.js/CommonJS packaging systems seems to preclude me from creating JavaScript files that can be used on both sides.(但是,Node.js / CommonJS打包系统似乎阻止我创建可以在双方使用的JavaScript文件。)

I also tried using JS.Class to get a tighter OO model, but I gave up because I couldn't figure out how to get the provided JavaScript files to work with require().(我也尝试使用JS.Class来获得更紧密的OO模型,但我放弃了,因为我无法弄清楚如何让提供的JavaScript文件与require()一起使用。)

Is there something am I missing here?(这里有什么我想念的吗?)   ask by Simon Cave translate from so

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

1 Reply

0 votes
by (71.8m points)

If you want to write a module that can be used both client side and server side, I have a short blog post on a quick and easy method: Writing for Node.js and the browser , essentially the following (where this is the same as window ):(如果你想编写一个可以在客户端和服务器端使用的模块,我有一个简短的博客文章,快速简单的方法: 为Node.js和浏览器编写 ,基本上如下( this是相同的window ):)

(function(exports){

    // Your code goes here

   exports.test = function(){
        return 'hello world'
    };

})(typeof exports === 'undefined'? this['mymodule']={}: exports);

Alternatively there are some projects aiming to implement the Node.js API on the client side, such as Marak's gemini .(或者,有一些项目旨在在客户端实现Node.js API,例如Marak的gemini 。)

You might also be interested in DNode , which lets you expose a JavaScript function so that it can be called from another machine using a simple JSON-based network protocol.(您可能还对DNode感兴趣,它允许您公开JavaScript函数,以便可以使用简单的基于JSON的网络协议从另一台计算机调用它。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...