How do I set up a preload file for node?

2020-06-21 07:52发布

Is there a way to preload some file before each time I run node (interactively), just like .vimrc, .bash_profile, etc.?

I use node mainly interactively, and I use the module CSV a lot, is there a way to avoid typing require('./csv') every time I start node?

标签: node.js
2条回答
劫难
2楼-- · 2020-06-21 08:03

@Ilan Frumer provided one way to do it. I think I'll give another choice here: build a REPL of your own.

From their documentation. You can find a way to write a repl of your own. You can add whatever scripts before and after the interations of it, and even use some advance API's.

For example, I created a file called .noderc.js under ~ as follows

repl = require('repl');

myFunc = function(){
    console.log("Hello, there!");
};

repl.start("> ");

And you can go ahead and alias nodei="node ~/.noderc.js",

$ nodei
> myFunc()
Hello, there!
undefined
查看更多
甜甜的少女心
3楼-- · 2020-06-21 08:04

Create an initialization file (for example ~/.noderc):

var csv = require('csv');

// put a blank line at the end of the file

Now add this line to your shell config (.bashrc / .zshrc / whatever shell you use):

alias nodei="cat ~/.noderc - | node -i"

Voilà!

查看更多
登录 后发表回答