开发者

Change current folder in Node.js

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜