【问题标题】:call require not possible in other file .js for nodeJs and express project在 nodeJs 和 express 项目的其他文件 .js 中调用 require 是不可能的
【发布时间】:2018-07-24 23:12:31
【问题描述】:

在项目nodeJS - express中,通过npm安装模块后,当app.js const cf = require('create-file')中需要“create-file”模块时,我不能在main.js中使用它,在控制台我有这个返回@ 987654322@ 当我运行节点时。

app.js

`   const express = require('express');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const cf = require('create-file');
// init app
const app = express();
//Template engine setup
app.set('view engine','html');
app.engine('html',ejs.renderFile);
// Index route
app.get('/',(req, res) => { 
res.render('index.html');
})
// Public folder setup
app.use(express.static(__dirname + '/public'));
// Body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
//  Catch from submit
app.post('/', (req, res) => {
res.send(req.body);
})
// Define port
const port = 3030;
// Start server

const server = app.listen(port, () => console.log( '服务器在端口启动 3030 '));`

main.js

`const button12 = document.getElementById('button');
button12.onclick = function () {
cf('C:\Users\tmeda\Bureau\fileTest.txt', 'my content\n', function (err) {
// file either already exists or is now created (including non existing 
directories) 
 });
 }`

【问题讨论】:

  • 为什么不在 main.js 中再要求一次?
  • 我不能,require is not defined
  • 尝试编辑您的问题并添加您的代码,我认为您只是缺少一些东西
  • @YouneL 有想法吗?
  • 您不能在客户端使用 create-file 包,它只能从服务器获得,而且浏览器不会让您出于安全目的创建文件,问题是您为什么要创建一个客户端机器上的文件?

标签: node.js express


【解决方案1】:

在 app.js 文件中将变量定义为全局变量

点赞global.cf = require('create-file');

这样你就可以在任何文件中访问cf变量,不需要在不同的文件中再次要求它。

【讨论】:

  • cf is not defined 当我尝试在 main.js 中使用 cf 时
  • 小拼写错误,使用global而不是globle
  • 不工作还是同样的问题,可能是因为我的项目的架构?
  • const express = require('express'); const ejs = require('ejs'); const bodyParser = require('body-parser'); global.cff = require('create-file'); const app = express(); app.set('view engine','html'); app.engine('html',ejs.renderFile); app.get('/',(req, res) => { res.render('index.html'); }) app.use(express.static(__dirname + '/public')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.post('/', (req, res) => { res.send(req.body); })const port = 3030; const server = app.listen(port, () => console.log( Server 在端口 ${port} 上启动 ));
  • 使用npm i --save create-file
猜你喜欢
  • 1970-01-01
  • 2013-08-30
  • 2017-10-28
  • 1970-01-01
  • 1970-01-01
  • 2014-03-06
  • 1970-01-01
  • 1970-01-01
  • 2011-02-27
相关资源
最近更新 更多