考虑到以下几点:
conversations.json
: []
db.js
let fs = require('fs');
let conversations = require('./conversations.json');
function addConversation(conversation){
console.log(conversations);
conversations.push(conversation);
try{
fs.writeFileSync('conversations.json', JSON.stringify(conversations));
}
catch(err){
console.error('Parse/WriteFile Error', err)
}
}
module.exports = {
addConversation
}
app.js
:
let database = require('./db.js');
database.addConversation(
{
key1: '1233',
key2: '433',
key3: '33211'
}
);
正在运行。node app.js
没有出现错误。一切都按预期编译。问题是 conversations.json
的时候没有更新。addConversation
函数从 app.js
.
有趣的是,一旦 addConversation
内被称为 db.js
万事大吉 conversations.json
正在更新。
我缺少什么?
我错过了什么?
可能是作为模块加载时,你把文件写入了错误的目录。
当你这样做的时候。
fs.writeFileSync('conversations.json', JSON.stringify(conversations));
这样写的时候 conversations.json
到当前工作目录,这个目录可能是也可能不是您的模块目录。 如果您想把它写到您的模块目录下,也就是这个。
let conversations = require('./conversations.json');
将从这里读取,那么您需要使用 __dirname
来制造合适的路径。
fs.writeFileSync(path.join(__dirname, 'conversations.json'), JSON.stringify(conversations));
require()
当你使用 ./filename
但 fs.writeFileSync()
使用当前的工作目录,而不是模块的目录。