{"id":13670880,"url":"https://github.com/luoshaohua/require-node","last_synced_at":"2025-04-27T13:33:06.081Z","repository":{"id":57354298,"uuid":"158815328","full_name":"luoshaohua/require-node","owner":"luoshaohua","description":null,"archived":false,"fork":false,"pushed_at":"2019-12-07T09:15:49.000Z","size":28,"stargazers_count":9,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-21T17:40:02.581Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/luoshaohua.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-11-23T10:10:13.000Z","updated_at":"2022-06-30T10:10:23.000Z","dependencies_parsed_at":"2022-09-26T20:20:30.282Z","dependency_job_id":null,"html_url":"https://github.com/luoshaohua/require-node","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luoshaohua%2Frequire-node","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luoshaohua%2Frequire-node/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luoshaohua%2Frequire-node/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luoshaohua%2Frequire-node/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/luoshaohua","download_url":"https://codeload.github.com/luoshaohua/require-node/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251145734,"owners_count":21543092,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T09:00:51.824Z","updated_at":"2025-04-27T13:33:01.069Z","avatar_url":"https://github.com/luoshaohua.png","language":"JavaScript","readme":"# require-node\r\n## A node middleware let that browser js code can require node js code which is still running at node server\r\n\r\n### *Example for how to use `require-node` in [https://github.com/luoshaohua/require-node-example](https://github.com/luoshaohua/require-node-example)*\r\n\r\n---\r\n\r\nrequire-node: In client(eg: Browser), you can REQUIRE and CALL server side javascript which is still running at server(eg: Node.js).\r\n\r\nrequire-node 让您能在前端（比如：浏览器）require后端javascript代码并调用，而这些后端代码在执行时依然在服务器上执行，而非浏览器里。\r\n\r\nFor example: A javascript module(test.js) in Node server, you can require and call that in Browser, like this:\r\n\r\n比如：您在Node服务器有一个模块test.js，您可以在浏览器中如下引用并调用：\r\n\r\n**In Browser code :**\r\n```\r\nvar test = require('path/to/test.js')\r\n\r\nvar sum = await test.add(1, 2)     // sum = 3\r\nvar env = await test.getNodeEnv()  // env is server env value\r\n```\r\n**In Node server code (test.js) :**\r\n```\r\nexports.add = function (a, b) {\r\n    return a + b;\r\n}\r\n\r\nexports.getNodeEnv = function () {\r\n    return process.env;\r\n}\r\n```\r\nNote: also support `promise`、`async/await` and `import` grammar.\r\n\r\n## Installion\r\n```\r\n$ npm install require-node\r\n```\r\n\r\n## Use\r\n\r\n`middleware`: function (req, res, next) { ... }\r\n```\r\nvar requireNode = require('require-node')\r\nvar middleware = requireNode({ base: \"path/to/server\" })\r\n```\r\n\r\nYou can use this `middleware` in node HTTP :\r\n```\r\nrequire('http').createServer(function (req, res) {\r\n    middleware(req, res, function () {\r\n        //req that require-node not process\r\n    }\r\n})\r\n```\r\n\r\n**also**, you can use this `middleware` in node [EXPRESS](https://www.npmjs.com/package/express) :\r\n```\r\nvar express = require('express')\r\nvar app = express()\r\napp.use(middleware)\r\n```\r\n\r\n**or**, you can use this `middleware` in node [KOA](https://www.npmjs.com/package/koa) :\r\n```\r\nvar Koa = require('koa')\r\nvar app = new Koa()\r\napp.use((ctx, next) =\u003e {\r\n  var { req, res, body } = ctx;\r\n  req.body = body;\r\n  return middleware(req, res, next);\r\n})\r\n```\r\n\r\n---\r\n\r\n## Config options\r\n\r\n**1. base: '/path/to/server', `ONLY this config is necessary!`**\r\n\u003e Config which back end file or dir can be use in front end. `base` can be set `String`/`Array`/`Object`.\r\n\r\n**2. path: '/require-node'** (default)\r\n\u003e Config which url path to be use sending ajax.\r\n\r\n**3. isDebug: false** (default)\r\n\u003e Config require-node output log or not.\r\n\r\n**4. hook function**\r\n\u003e Sometimes, for some reason(example: `security` or `login`), we will prevent some function calls. For each http request before processing, require-node calls `preFetch` in Browser and calls `preCall` in Node Server (if throw error or return promise reject, call will be prevent), after server api function called, `postCall` will be call in Node Server and `postFetch` alse be call in Browser.\r\n\r\n**preFetch: function (options) { return promise or common value; }**  \r\n**preCall: function (options) { return promise or common value; }**  \r\n**postCall: function (apiReturn, options) { return a new apiReturn; }**  \r\n**postFetch: function (apiReturn, options) { return a new apiReturn; }**  \r\n\r\noptions's structure: { req, res, moduleName, functionNames, formalParams, actualParams }  \r\n`Note`: In Browser, `req` is xhr(`XMLHttpRequest`) object.\r\n\r\n**5. inject: function(req, res){ return {curUser: req.session \u0026\u0026 req.session.curUser}; }**\r\n\u003e Use inject config, you can define Custom Injected Services. For more details, please refer to the next section: Inject Service.\r\n\r\n## Inject Service\r\n**1. Use Default Service**\r\n\r\nIf your back end function want use variable `$req`、`$res`、`$session`、http `$body`, you can define back end function like this:\r\n```\r\nfunction say(arg1, arg2, $req, arg4, arg5){\r\n    console.log($req) // $req is node http req object\r\n}\r\nexports.say = say\r\n```\r\nrequire-node will inject variable req to $req.\r\n\r\n**2. Use Custom Service**\r\n\r\nIf want define Custom Injected Services, you can config like this(eg: curUser service):\r\n```\r\nvar middleware = require('require-node')({\r\n    base: \"path/to/server\"\r\n    inject: function(req, res){\r\n        return {\r\n            curUser: req.session \u0026\u0026 req.session.currentUser, //if you store currentUser in req.session\r\n            otherService: ...\r\n        }\r\n    }\r\n})\r\n```\r\nIn your back end function, you can use curUser like this:\r\n```\r\nfunction say(arg1, arg2, curUser, arg4, arg5){\r\n    console.log(curUser)\r\n}\r\nexports.say = say\r\n```\r\n\r\nThat's all.\r\n\r\n---\r\n\r\n*Example for how to use `require-node` in [https://github.com/luoshaohua/require-node-example](https://github.com/luoshaohua/require-node-example)*","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fluoshaohua%2Frequire-node","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fluoshaohua%2Frequire-node","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fluoshaohua%2Frequire-node/lists"}