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
127 views
in Technique[技术] by (71.8m points)

node.js - Using NPM modules

I'm currently learning about NPM modules and have a very basic question. Let's say I have my package.json file which looks like this:

{
  "version": "1.0.0",
  "main": "express.js",
  "dependencies": {
    "lodash": "^4.17.20",
  }
}

In my express.js file I can then require and use lodash like this:

const _ = require('lodash');
const numbers = [1,2,3,4,5,6];

_.each(numbers, function (number, i){
    console.log(number)
});

I now have two questions:

  1. How can I display this code in a basic HTML document instead of just the console?
  2. How can I require/use node modules in another js file? E.g. if I want to require lodash from another js file?

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

1 Reply

0 votes
by (71.8m points)

To answer your questions:

  1. There a several ways of doing this, perhaps the simplest is to use a template engine such as ejs to return html data to a client.

For example:

const express = require('express');
const app = express();
const ejs = require("ejs");

app.get('/', (req, res) => { 
    const fruits = ['apple', 'pear', 'banana'];
    const html = ejs.render(`<ul>
    <% for (let fruit of fruits) { %>
        <li> <%= fruit %> </li>
    <% } %>
    </ul>`, { fruits });
    res.status(200).send(html);
});

app.listen(3000);

Just run the script, then goto http://localhost:3000 to see the result.

  1. You should be able to use the same syntax to include modules in your other files, e.g. foo.js, just include:

    const _ = require("lodash");


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

...