开发者

Change current folder in Node.js

开发者 https://www.devze.com 2023-01-28 17:23 出处:网络
I have a file fetching some other files: start.js require("./users"); but the users.js file is not in the current folder but in model/.

I have a file fetching some other files:

start.js

require("./users");

but the users.js file is not in the current folder but in model/.

I want to be able to run:

node start.js model

开发者_运维问答and it would assume that ./ is the same as model/ in start.js.

How do I do that?


All you need to do is to make Node.js recognize the folder model as a module.

In order to do that, you need to place a file called index.js inside the model folder.

//  model/index.js
exports.users = require('./users'); //  model/users.js
exports.posts = require('./posts'); //  model/posts.js
// etc.

Now you can import the model module and access it's exports:

var models = require('./model');
models.users.create(); // some function exported in model/users.js
models.posts.list(); // this was exported in model/posts.js


You can add ./model dir to require.paths array:

require.paths.unshift("./model");
var
  users = require("users"), // It works!
  posts = require("posts");

But I want to ask you: why do you need this instead of using

var
  users = require("./model/users"), // It works!
  posts = require("./model/posts");

?

0

精彩评论

暂无评论...
验证码 换一张
取 消